Forum: Ruby on Rails assert_equal 1.1035, 1.0035 + 0.1 is false

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
jzimmek (Guest)
on 2009-01-23 18:50
(Received via mailing list)
some of my tests failed when comparing two floats.

the comparison of:

1.1035 == 1.0035 + 0.1

evaluates to false - i do not really understand why.

must depend on the value range, because

1.103 == 1.003 + 0.1

evaluates to true.

would be great if anyone could help me getting this working and maybe
giving an explanation why ruby do not handle the == operator for float
as one would expect (coming from java).

tested on:

1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0]

jan zimmek
Frederick C. (Guest)
on 2009-01-23 18:56
(Received via mailing list)
On 23 Jan 2009, at 16:49, jzimmek wrote:

> 1.103 == 1.003 + 0.1

basically because 0.1 cannot be exactly represented in binary.

assert_in_delta is good for this sort of stuff.

Bob M. (Guest)
on 2009-01-23 19:00
(Received via mailing list)
Crud, he beat me to it.

You're going to have to either change the logic or change the testing
procedure for it.

On Jan 23, 10:55 am, Frederick C. <removed_email_address@domain.invalid>
jzimmek (Guest)
on 2009-01-23 19:12
(Received via mailing list)
thanks for clarification ... have found some further explanations/
solutions and will change my testing-logic.

On Jan 23, 5:55 pm, Frederick C. <removed_email_address@domain.invalid>
Jeffrey L. Taylor (Guest)
on 2009-01-24 06:50
(Received via mailing list)
Quoting jzimmek <removed_email_address@domain.invalid>:
> 1.103 == 1.003 + 0.1

In general, exact comparisons of floating point numbers is a bad idea.
better idea is something along the lines of:

(value1 - value2).abs <= epsilon

epsilon may be a fixed value of a fraction of the values, maybe

epsilon = (value1 + value2) / 100

i.e. 1/50 the average of the two.  The best solution depends on the

This topic is locked and can not be replied to.