ruby floats add up to different values depending on the order

floating-point, ruby

Solution

Floating point operations are inexact: they round the result to nearest representable float value. That means that each float operation is:

float(a op b) = mathematical(a op b) + rounding-error( a op b )

As suggested by above equation, the rounding error depends on operands a & b. Thus, if you perform operations in different order,

float(float( a op b) op c) != float(a op (b op c))

In other words, floating point operations are not associative. They are commutative though...

As other said, transforming a decimal representation 0.1 (that is 1/10) into a base 2 representation (that is 1/16 + 1/64 + ... ) would lead to an infinite serie of digits. So float(0.1) is not equal to 1/10 exactly, it also has a rounding-error and it leads to a long serie of binary digits, which explains that following operations have a non null rounding-error (mathematical result is not representable in floating point)

Problem

So this is weird. I'm in Ruby 1.9.3, and float addition is not working as I expect it would. ``` 0.3 + 0.6 + 0.1 = 0.9999999999999999 0.6 + 0.1 + 0.3 = 1 ``` I've tried this on another machine and get the same result. Any idea why this might happen?

Original source