I am dealing with a code which uses very small numbers of order 10^-15 to 10^-25. I tried using double
and long double
but i get a wrong answer as either 0.000000000000000000001
is rounded off to 0
or a number like 0.00000000000000002
is represented as 0.00000000000000001999999999999
.
Since even a small fraction of 1/1000000 makes a huge difference in my final answers, is there an appropriate fix?
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
double sum, a, b, c,d;
a=1;
b=1*pow(10,-15);
c=2*pow(10,-14);
d=3*pow(10,-14);
sum=a+b+c+d;
cout<<fixed;
cout<<setprecision(30);
cout<<" a : "<<a<<endl<<" b : "<<b<<endl<<" c : "<<c<<endl
<<" d : "<<d<<endl;
cout<<" sum : "<<sum<<endl<<endl;
a=a/sum;
b=b/sum;
c=c/sum;
d=d/sum;
sum=a+b+c+d;
cout<<" a : "<<a<<endl<<" b : "<<b<<endl<<" c : "<<c<<endl
<<" d : "<<d<<endl;
cout<<" sum2: "<<sum<< endl;
return 0;
}
The expected output should be:
a : 1.000000000000000000000000000000
b : 0.000000000000001000000000000000
c : 0.000000000000020000000000000000
d : 0.000000000000030000000000000000
sum : 1.000000000000051000000000000000
a : 1.000000000000000000000000000000
b : 0.000000000000001000000000000000
c : 0.000000000000020000000000000000
d : 0.000000000000030000000000000000
sum1: 1.000000000000051000000000000000
But, the output I get is:
a : 1.000000000000000000000000000000
b : 0.000000000000001000000000000000
c : 0.000000000000020000000000000000
d : 0.000000000000029999999999999998
sum : 1.000000000000051100000000000000
a : 0.999999999999998787999878998887
b : 0.000000000000000999999997897899
c : 0.000000000000019999999999999458
d : 0.000000000000029999999999996589
sum1: 0.999999999999989000000000000000
I tried double
, long double
and even boost_dec_float
, but the output I get are similar.