patternModerate
What is the reason of inaccuracy of operations on float numbers?
Viewed 0 times
theoperationswhatfloatnumbersinaccuracyreason
Problem
I wonder why in JavaScript
http://jsbin.com/oHISAfU/1/edit (Example)
In C the math.h library fmod function
http://ideone.com/RG5Wyv (Example)
And in Spotlight (search feature in the Mac OS X ~ I already submit bug report) that support math operation
0.1 + 0.2 // return 0.30000000000000004
4%0.1 // return 0.09999999999999978http://jsbin.com/oHISAfU/1/edit (Example)
In C the math.h library fmod function
printf("%f", fmod(4.0,0.1)); // print 0.100000http://ideone.com/RG5Wyv (Example)
And in Spotlight (search feature in the Mac OS X ~ I already submit bug report) that support math operation
4%0.1 = 0.1Solution
It's because 0.1 = 1 / 10 = 1 / (2 × 5) cannot be represented exactly in binary floating point. This happens in C too:
prints
Specifically, the only numbers that binary floating point can represent exactly are dyadic fractions of the form a / 2b, where a and b are integers. Even more specifically, for IEEE single precision floating point numbers, a must be between -224 and 224 and b must, in effect, be between -151 and 104. (Or at least approximately so; there are some tricky special cases like denormalized numbers.) For double precision floats, the ranges are wider, but even so, a fraction like 1 / 10 cannot be represented exactly, because the denominator is not a power of two.
printf("%.20f", fmod(4.0,0.1));prints
0.09999999999999978351.Specifically, the only numbers that binary floating point can represent exactly are dyadic fractions of the form a / 2b, where a and b are integers. Even more specifically, for IEEE single precision floating point numbers, a must be between -224 and 224 and b must, in effect, be between -151 and 104. (Or at least approximately so; there are some tricky special cases like denormalized numbers.) For double precision floats, the ranges are wider, but even so, a fraction like 1 / 10 cannot be represented exactly, because the denominator is not a power of two.
Code Snippets
printf("%.20f", fmod(4.0,0.1));Context
StackExchange Computer Science Q#13810, answer score: 15
Revisions (0)
No revisions yet.