Conditional Loop question

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.

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 R.

On Sun, Dec 9, 2012 at 8:11 AM, Ivan S. [email protected] 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 :slight_smile: