Reputation: 61
I'm using double instead of float in my code but unfortunately i faced the next problem : When i try to add :
1.000000000000020206059048177849 + 0.000000000000020206059048177849
i have this result :
1.000000000000040400000000000000
which avoid the last 14 number.. i want the result to be more accurate. i know this might look silly but really this is so important to me .. anyone can help?
here's a simple code example :
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
double a=1.000000000000020206059048177849 + 0.000000000000020206059048177849;
cout<<fixed<<setprecision(30)<<a;
system("pause");
return 0;
}
Upvotes: 2
Views: 149
Reputation: 4118
Update: The answer below assumes that the expression is evaluated during run-time, i.e. you are not adding compile-time constants. This is not necessarily true, your compiler may evaluate the expression during compile time. It may use higher precision for this. As suggested in the comments, the way you print out the number might be the root cause for your problem.
If you absolutly need more precision and can't make any other twists, your only option is to increase precision. double
values provide a precision of about 16 decimal digits. You have the following options:
Use a library that provides higher precision by implementing floating point operations in software. This is slow, but you can get as precise as you want to, see e.g. GMP, the GNU Multiple Precision Library.
The other option is to use a long double
, which is at least as precise as double
. On some platforms, long double
may even provide more precision than a double
, but in general it does not. On your typical desktop PC it may be 80
bits long (compared to 64
bits), but this is not necessarily true and depends on your platform and your compiler. It is not portable.
Maybe, you can avoid the hassle and tune your implementation a bit in order to avoid floating point errors. Can you reorder operations? Your intermediate results are of the form 1+x
. Is there a way to compute x
instead of 1+x
? Subtracting 1
is not an option here, of course, because then precision of x
is already lost.
Upvotes: 1