c++ - modf returns 1 as the fractional: -
i have static method, receives double , "cuts" fractional tail leaving 2 digits after dot. works almost time. have noticed when receives 2.3 turns 2.29. not happen 0.3, 1.3, 3.3, 4.3 , 102.3. code multiplies number 100 uses modf divides integer value 100 , returns it. here code catches 1 specific number , prints out:
static double dround(double number) { bool c = false; if (number == 2.3) c = true; int factor = pow(10, 2); number *= factor; if (c) { cout << " number *= factor : " << number << endl; //number = 230;// when not marked comment code works well. } double returnval; if (c){ cout << " fractional : " << modf(number, &returnval) << endl; cout << " integer : " <<returnval << endl; } modf(number, &returnval); return returnval / factor; }
it prints out:
number *= factor : 230
fractional : 1
integer : 229
does know why happening , how can fix this? thank you, , have great weekend.
remember floating point number cannot represent decimal numbers exactly. 2.3 * 100 gives 229.99999999999997. modf
returns 229 , 0.9999999999999716.
however, cout
's format display floating point numbers 6 decimal places default. 0.9999999999999716 shown 1.
you use (roughly) upper error limit value represents in floating point avoid 2.3 error:
#include <cmath> #include <limits> static double dround(double d) { double inf = copysign(std::numeric_limits<double>::infinity(), d); double thenumberafter = nextafter(d, inf); double epsilon = thenumberafter - d; int factor = 100; d *= factor; epsilon *= factor/2; d += epsilon; double returnval; modf(number, &returnval); return returnval / factor; }
result: http://www.ideone.com/ywmua
Comments
Post a Comment