# Forum: Ruby Conditional Loop question

on 2012-12-09 17:11
Attachment: Selecci__n_002.jpeg (11,1 KB)
Hi everybody,

can someone explain the behaviour of this simple loop that doesnt stop
in
1.13.

>> x =1.12
=> 1.12
>> loop do
?> x=x+0.01
>> break if (x==1.13 || x > 1.19)
>> puts x
>> end
1.13
1.14
1.15
1.16
1.17
1.18
=> nil

thanks.
on 2012-12-09 17:49
This is because floating-point numbers are not exact.

irb(main):002:0> a = 1.12
=> 1.12
irb(main):003:0> b = 1.13
=> 1.13
irb(main):004:0> a + 0.01 == b
=> false
irb(main):005:0> a + 0.01
=> 1.1300000000000001

-- Matma Rex
on 2012-12-09 17:54
On Sun, Dec 9, 2012 at 8:11 AM, Ivan S. <lists@ruby-forum.com> wrote:

> can someone explain the behaviour of this simple loop that doesnt stop
> in 1.13.
>
>>> x =1.12
> => 1.12
>>> loop do
> ?> x=x+0.01
>>> break if (x==1.13 || x > 1.19)

1.9.3 (main):0 > 1.13 == 1.13
=> true
1.9.3 (main):0 > 1.13 == (1.12 + 0.01)
=> false
1.9.3 (main):0 > 1.12 + 0.01
=> 1.1300000000000001
1.9.3 (main):0 > BigDecimal.new("1.13") == ( BigDecimal.new("1.12") +
BigDecimal("0.01") )
=> true

Floating Point strikes again :-)