1.15 * 100 = 149.99999999999999 except in Ruby
All I've tried (Haskell (GHC), Python, Erlang, Clojure, Ruby) except Ruby give 149.99999999999999. What IEEE floating point (double/single precision) standard is causing this :) and why doesn't it happen in Ruby?
$ ghic
Prelude> 1.15 * 100
114.99999999999999
$ python
>>> 1.15 * 100
114.99999999999999
$ erl
1> 1.15 * 100.
114.99999999999999
$ irb
>> 1.15 * 100
=> 115.0
22 comments
[ 2.6 ms ] story [ 67.4 ms ] thread* (* 1.15 100) 115.0
Enter 1.15 and marvel how mantissa is represented:
1.0010011001100110011001100110011001100110011001100110
The whole FP number in hex is: 3ff2666666666666
if there were more bits, 1100 would still continue to repeat. But you have to store that number in fixed number of bits. Whichever fixed number of bits you select, you'll miss the infinite piece of repeats! Modern CPUs and languages represent the whole number in 8 bytes, using binary base, taking a few bits for the exponent. The above number is
So now you multiply that with decimal 100. The result is still a series of repeats: Whereas exact 115 would be: Why do we get one bit difference? Because we started from the finite binary representation of "1.15" that is not equivalent to your decimal "1.15".If you don't want such things to happen, you should use:
http://en.wikipedia.org/wiki/Decimal_floating_point
We write only decimal representations, and such representation used internally would always provide the "expected" results.
Currently no Intel processor supports such numbers in hardware, therefore such numbers are seldom present in languages.
As far as I know only IBM processors have hardware implementation of such numbers:
http://www.ibm.com/developerworks/wikis/display/hpccentral/H...
Your Ruby executable just rounds the binary represented result before displaying as decimal. It depends on the conversion libraries used and default rounding limits.