Re: BUG! Erratic for loop behavior
- Posted by rforno at tutopia.com Mar 23, 2002
- 469 views
Of course you are right. The desirable behavior is that lost precision does not interfere with exact results. But the solution to this problem is costly in processing time. Should Euphoria fix it, it would be much slower. There are a couple of programming languages where this problem does not practically exist. These are APL (in which a fuzz is considered in comparisons) and ABC (a language from the Netherlands, which does arithmetic with [nearly] infinite digits, and that does not lose precision even after assigning a number such as 0.3 to a variable). But they are much slower than Euphoria. Regards. ----- Original Message ----- From: "Andy Serpa" <renegade at earthling.net> To: "EUforum" <EUforum at topica.com> Subject: RE: BUG! Erratic for loop behavior > > 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"? > > > > > > >