floating point - Handling extremly small numbers in C++ -
let , b 2 numbers between 0 , 1. how calculate pow(a,10000)/(pow(a,10000)+pow(b,10000))
?
ex:- following code gives -nan output instead of 0.5
double = 0.5,b = 0.5; cout<<pow(a,10000)/(pow(a,10000)+pow(b,10000));
there no simple generic solution problem. writing computer programs dealing small and/or big numbers "art of science" - called numerical analysis. typical tricks involves scaling before calculating.
in case each pow(..) rounded 0 because closest representable value real result. after 0/(0 + 0) nan, i.e. not number.
you go long double:
long double = 0.5; long double b = 0.5; long double c =pow(a,10000); long double d =pow(b,10000); cout << c << endl; cout << d << endl; cout<<c/(c+d);
which result in:
5.01237e-3011 5.01237e-3011 0.5
but " while". increasing power bit (just zero) , problem back.
long double = 0.5; long double b = 0.5; long double c =pow(a,100000); long double d =pow(b,100000); cout << c << endl; cout << d << endl; cout<<c/(c+d); 0 0 nan
so need write complicated class or study how handle in numerical analysis.
start here: https://en.wikipedia.org/wiki/numerical_analysis or https://en.wikipedia.org/wiki/arbitrary-precision_arithmetic
if know exp same 3 place can do:
double = 0.5,b = 0.5; int exp = 10000; //cout<<pow(a,exp)/(pow(a,exp)+pow(b,exp)); same as: cout<<1/(1+pow(b/a,exp));
it work better , b values don't expect precision. if , b differs little bit, you'll 0 (for less b) or 1 (for b less a). nan part solved.
Comments
Post a Comment