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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C22c46a54673d3f35910b1a4199ee80f?d=identicon&s=25 jzimmek (Guest)
on 2009-01-23 17: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]


regards
jan zimmek
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-01-23 17: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.

Fred
247cd3d37084a3d6794076207bd9fbd7?d=identicon&s=25 Bob Martens (Guest)
on 2009-01-23 18: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 Cheung <frederick.che...@gmail.com>
C22c46a54673d3f35910b1a4199ee80f?d=identicon&s=25 jzimmek (Guest)
on 2009-01-23 18: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 Cheung <frederick.che...@gmail.com>
96146b7a23174e2e024c06a49f845bb8?d=identicon&s=25 Jeffrey L. Taylor (Guest)
on 2009-01-24 05:50
(Received via mailing list)
Quoting jzimmek <jan.zimmek@web.de>:
>
> 1.103 == 1.003 + 0.1
>

In general, exact comparisons of floating point numbers is a bad idea.
A
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
particular
problem.

Jeffrey
This topic is locked and can not be replied to.