Re: crazy loops [message #29344 is a reply to message #29338] |
Wed, 13 February 2002 09:14   |
Robert Stockwell
Messages: 74 Registered: October 2001
|
Member |
|
|
M Carmen wrote:
> Hello,
>
> I have a question related with loops......can someone teel me why
>
> if i do a loop that goes to a maximum of 0.6:
> for r=0.0, 0.6, 0.1 do begin & print, r & endfor
>
> I get:
> 0.000000
> 0.100000
> [........]
> 0.500000
> 0.600000
>
> and if now i change the maximum value of the range to 0.7:
> for r=0.0, 0.7, 0.1 do begin & print, r & endfor
>
> I get:
> 0.000000
> 0.100000
> [........]
> 0.500000
> 0.600000
>
> EXACTLY THE SAME!!!
>
> I have IDL Version 5.4
>
> Thanks :) !
> M Carmen
One should exercise great care when comparing the results of floating
point calculations:
(If these wrap around on your read, i apologize.)
run these lines:
IDL> limit = 0.7 & for r=0.0, limit, 0.1 do print, r,limit,r le limit,format='(f50.25,f50.25,f8.4)'
0.0000000000000000000000000 0.6999999880790710449218750 1.0000
0.1000000014901161193847656 0.6999999880790710449218750 1.0000
0.2000000029802322387695312 0.6999999880790710449218750 1.0000
0.3000000119209289550781250 0.6999999880790710449218750 1.0000
0.4000000059604644775390625 0.6999999880790710449218750 1.0000
0.5000000000000000000000000 0.6999999880790710449218750 1.0000
0.6000000238418579101562500 0.6999999880790710449218750 1.0000
IDL> limit = 0.6 & for r=0.0, limit, 0.1 do print, r,limit,r le limit,format='(f50.25,f50.25,f8.4)'
0.0000000000000000000000000 0.6000000238418579101562500 1.0000
0.1000000014901161193847656 0.6000000238418579101562500 1.0000
0.2000000029802322387695312 0.6000000238418579101562500 1.0000
0.3000000119209289550781250 0.6000000238418579101562500 1.0000
0.4000000059604644775390625 0.6000000238418579101562500 1.0000
0.5000000000000000000000000 0.6000000238418579101562500 1.0000
0.6000000238418579101562500 0.6000000238418579101562500 1.0000
The for loop checks r le upper limit, and then executes if true.
Here, 0.6 is actually a little gt 0.600000000000, and 0.7 is just less than 0.700000000000000000000000000.
Hence the seemingly goofy results.
Cheers,
bob
PS to explain why you do not see the limit = 0.7 case, for that iteration
r = 0.7099999785423278808593750 and the limit is 0.6999999880790710449218750.
|
|
|