From: Julian Leviston Date: 2009-11-22T12:17:14+09:00 Subject: Re: really crazy about this (do/while) My guess is because floats aren't exact, so adding .1 ten times isn't precisely the same as adding 1. Use BigDecimal if you wanna be really accurate. Julian Blog: http://random8.zenunit.com/ Twitter: http://twitter.com/random8r Learn: http://sensei.zenunit.com/ New video up now at http://sensei.zenunit.com/ real fastcgi rails deploy process! Check it out now! On 22/11/2009, at 2:09 PM, Ruby Newbee wrote: > Hello, > > Please see the code and running result below: > > # > # case one > # > [root@localhost tmp]# cat t5.rb > temp = 98.4 > i = 0 > > begin > i += 1 > puts "step" + i.to_s + " befre adding is " + temp.to_s > temp += 0.1 > puts "step" + i.to_s + " after adding is " + temp.to_s > puts > end while temp < 98.6 > > > [root@localhost tmp]# ruby t5.rb > step1 befre adding is 98.4 > step1 after adding is 98.5 > > step2 befre adding is 98.5 > step2 after adding is 98.6 > > > OK I think the result is pretty right. > > Now I change temp's original value to 98.3: > > # > # case two > # > [root@localhost tmp]# cat t5.rb > temp = 98.3 > i = 0 > > begin > i += 1 > puts "step" + i.to_s + " befre adding is " + temp.to_s > temp += 0.1 > puts "step" + i.to_s + " after adding is " + temp.to_s > puts > end while temp < 98.6 > > > [root@localhost tmp]# ruby t5.rb > step1 befre adding is 98.3 > step1 after adding is 98.4 > > step2 befre adding is 98.4 > step2 after adding is 98.5 > > step3 befre adding is 98.5 > step3 after adding is 98.6 > > step4 befre adding is 98.6 > step4 after adding is 98.7 > > > The output of step4 let me crazy. > Why the loop doesn't break after step3? > Because after step3 temp's value is 98.6, the loop condition was > checked, and the loop should be end. > > Since I think case one is right, so case two get wrong result. Why? > Thank you. >