#101157 - 2003-05-20 08:46 PM
When is 0.1 - 0.1 NOT 0?
|
Chris S.
MM club member
   
Registered: 2002-03-18
Posts: 2368
Loc: Earth
|
I was playing around with a Mandrelbot script when I noticed that For...Next Loops do not accept Double Integers, i.e.:
code:
Break On For $x = 1.1 to 2.1 step 0.1 $x ? Next
I was about to make post a topic in Suggestions about it, but was wise enough to run it across Jens first. The short of it is... quote: Numbers can only be represented digitally with an accuracy of EPS. Thus, a number x+EPS/2 canot be represented and will be either end up being x or x+EPS
His suggestion was to use a Do...Until or While...Loop loop. So, I tried this... code:
$x = 1.2
While $x > -1.2 $x ? $x = $x - 0.1 Loop
...which has some interesting results when 0 is expected.
Thoughts???? [ 20. May 2003, 20:47: Message edited by: Chris S. ]
|
|
Top
|
|
|
|
#101163 - 2003-05-21 01:44 PM
Re: When is 0.1 - 0.1 NOT 0?
|
Richard H.
Administrator
   
Registered: 2000-01-24
Posts: 4946
Loc: Leatherhead, Surrey, UK
|
The K&R 'C' manual (aka The Bible) explicitly warns about this, and advizes the use of fuzzy checks, i.e.:
code:
BAD : If $x = 0 GOOD : If ($x>=-0.01 AND $x <=0.01)
Or whatever your margin of error is. As the guys say, is better to stick to integer maths and convert. Your first example would become:
code:
Break ON For $x = 11 To 21 Cdbl($x)/10 ? Next
|
|
Top
|
|
|
|
Moderator: Arend_, Allen, Jochen, Radimus, Glenn Barnas, ShaneEP, Ruud van Velsen, Mart
|
0 registered
and 1046 anonymous users online.
|
|
|