1

I'm handling some mathematical calculation. I'm losing precision. But i need extreme precision. I then used to check the precision issue with the code given below. Any solution for getting the precision?

#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sstream>
#include <iomanip>
using namespace std;



int main(int argc,char** arvx)
{
   float f = 1.00000001;
   cout << "f: " <<std::setprecision(20)<< f <<endl;
   return 0;
}

Output is f: 1

kjk
  • 116
  • 1
  • 11
  • Step 1 is to not use `float`. Use `double`, which has about 16 digits of precision and should always be your first choice for storing real numbers. Do you need more than 16 significant digits? – user2357112 Mar 04 '14 at 05:22
  • [Not if you store it in a double](http://coliru.stacked-crooked.com/a/d9dbfa7280e8f9d1) (Maybe boost::multiprecision would be good too) – Borgleader Mar 04 '14 at 05:23

2 Answers2

1

If you truly want precise representation of these sorts of numbers (ie, with very small fractional components many places beyond the decimal point), then floating point types like float or even the much more precise double may still not give you the exact results you are looking for in all circumstances. Floating point types can only approximate some values with small fractional components.

You may need to use some sort of high precision fixed point C++ type in order to get exact representation of very small fractions in your values, and resulting accurate calculated results when you perform mathematical operations on such numbers. The following question/answers may provide you with some useful pointers: C++ fixed point library?

Community
  • 1
  • 1
Ozraptor
  • 554
  • 4
  • 11
0

in c++

float f = 1.00000001;

support only 6 digits after decimal point

float f = 1.000001;

if you want more real calculation use double

Rishi Dwivedi
  • 908
  • 4
  • 19
  • 1
    in using double, 1.00000001 is shown as 1.0000000099999999392 – kjk Mar 04 '14 at 05:29
  • 4
    @KiranJose [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Borgleader Mar 04 '14 at 05:29
  • 1
    '6 digits after the decimal point' simply isn't correct. '6 decimal digits of total precision' would be more like it, but after the decimal point this can take much larger forms as you are dividing, not multiplying. Consider e.g. 2^-10. – user207421 Mar 04 '14 at 07:01