简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM