kjk
kjk

Reputation: 126

c++ precision issue in storing floating point numbers

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

Upvotes: 1

Views: 2174

Answers (2)

Ozraptor
Ozraptor

Reputation: 564

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?

Upvotes: 1

Rishi Dwivedi
Rishi Dwivedi

Reputation: 928

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

Upvotes: 0

Related Questions