RE: BUG! Erratic for loop behavior
- Posted by Andy Serpa <renegade at earthling.net> Mar 23, 2002
- 466 views
Here's another example: atom sum sum = 60.0 for i = 1 to 45 do sum += .1 end for ? sum ? equal(sum,64.5) ? (sum = 64.5) Output is: 64.5 0 0 Please don't tell me this is desirable behavior. Explaining the cause of the problem doesn't remove the problem. I am well aware of how computers represent numbers but since I'm only dealing with one decimal place I should get at least that much precision (actually, reverse that -- I am getting too much precision) when doing comparsions... Andy Serpa wrote: > > Rolf Schröder wrote: > > Andy Serpa wrote: > > > ... > > > ------------------------------ > > > for i = 31.1 to 34.2 by .1 do > > > ? i > > > end for > > > ------------------------------ > > > stops at 34.1 (!), NOT as expected. > > > > > Hi Andy, > > > > that's ok. Look at this: > > > > for i = 31.1 to 34.1 by 0.1 do > > printf(1,"%20.15f\n",i) > > end for > > > > and you will notice why: the decimal given value 0.1 is exactly > > representable in the computer for it has to stores it internally as an > > binary value with a limited number of bits. Actually, 0.1 (dec.) is has > > an unlimited binary representation: 0.0001100110011..... . This is the > > correct way to do it (have in mind that 31.1 and 34.1 are also not > > exactly representable!): > > > > for i = 311 to 341 by 1 do > > printf(1,"%20.15f\n",i/10) > > end for > > > > Yeah, that's not really good enough for me -- .1 should be .1 in a loop. > The Euphoria manual even has an example under the FOR loop section > using a .3 "by" value... Is this also a "feature"? > >