News for hackers. Stuff that matters.
Re:1.15 * 100 = 149.99999999999999 except in Ruby by acqq on Friday December 16, 2011 @12:26PM (#3361311)
It's all about the infinite numbers of bits that get lost as soon as the decimal fraction is converted in binary. See http://babbage.cs.qc.edu/IEEE-754/

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

  3ff2666666666666
So now you multiply that with decimal 100. The result is still a series of repeats:

  405cbfffffffffff
Whereas exact 115 would be:

  405cc00000000000
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.

There are no comments on this comment yet.