Luc Moulinier wrote:
> set Llim -99999999999.
> set v -2.0
> while {$v <= 2.} {
> lappend Llim $v $v
> set v [expr {$v + 0.1}]
> }
> lappend Llim 99999999999.
>
> Output:
> -99999999999. -2.
> -2. -1.9
> -1.9 -1.7999999999999998
> -1.7999999999999998 -1.6999999999999997
> -1.6999999999999997 -1.5999999999999996
> -1.5999999999999996 -1.4999999999999996
> -1.4999999999999996 -1.3999999999999995
> ..........
> ..........
> 1.7000000000000013 1.8000000000000014
> 1.8000000000000014 1.9000000000000015
> 1.9000000000000015 99999999999.
>
> I miss the 1.9 2. couple.
Continuing in an interactive tclsh...
% set v
2.0000000000000013
% expr {$v <= 2.}
0
So by the conditions you set for the loop, that value should not
go onto the list.
Your real question is "Why can't I get exactly correct results when
I repeatedly add the value 0.1? Why am I getting these rounding
errors?"
The reason is that computers do their figuring in base 2, and there's
no number of bits that can represent the value 0.1 exactly. Contrast
with the values 0.5, 0.25, 0.125, which you can demand exact
representation. This means roundoff issues are unavoidable, and you
must write code that's aware of that. Testing for equality of
floating point values as a condition to take a branch or end a loop
is usually the wrong thing to do because of this.
Two broad alternatives to dealing with this. First, relax the equality
test to something looser [if {$v < 2.+$epsilon} ...] where $epsilon
is chosen suitable to the needs of your problem. Second, do your
counting and looping in the domain of integers, which are exactly
represented.
set v -20
while {$v <= 20} {
set val [expr {$v*0.1}]
lappend Llim $val
incr v
}
These issues are encountered very early when learning to do numeric
computing. I'm surprised you're not already familiar with them.
--
| Don Porter Applied and Computational Mathematics Division |
|
donald...@nist.gov Information Technology Laboratory |
|
http://math.nist.gov/~DPorter/ NIST |
|______________________________________________________________________|