Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Floating point increment bugs out. Incr should take float

140 views
Skip to first unread message

TERRENCE MONROE BRANNON

unread,
Apr 15, 1993, 10:48:36 AM4/15/93
to

[1] incr should take a float argument -- i dont see why not

[2] the following bugs out:

for {set i 0.0} {$i != 1.0} {set i [expr $i+0.1]} {
echo $i
}

resulting in:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.1
1.2

.. and so forth until infinity
--
Terry Brannon tbra...@lion.eecs.lehigh.edu
medical biology via acupunctural bioelectrics
primitive reigns supreme over nearly everyone

Keith Steiger

unread,
Apr 15, 1993, 6:30:43 PM4/15/93
to
In article <TB06.93Ap...@CS2.CC.Lehigh.EDU> tb...@CS2.CC.Lehigh.EDU (TERRENCE MONROE BRANNON) writes:
>[1] incr should take a float argument -- i dont see why not

Because then the result would have to be a float, and some people don't wamt
their numbers gratuitously changed to floats when they're not looking. Or use

proc incrf {v {i 1.0}} {upvar 1 $v x; set x [expr $x+$i]}

>[2] the following bugs out:
> for {set i 0.0} {$i != 1.0} {set i [expr $i+0.1]} {
> echo $i
> }
>resulting in:
>0.0
>0.1
>0.2
>0.3
>0.4
>0.5
>0.6
>0.7
>0.7999999999999999
>0.8999999999999999
>0.9999999999999999
>1.1
>1.2
>.. and so forth until infinity

Two options:
for {set i 0.0} {$i <= 0.99} {incrf i 0.1} {echo $i}
for {set i 0} {$i != 10} {incr i} {echo [expr $i/10.0]}

The second of these gets much better accuracy on its results by holding off
on the switch to floating point as long as possible, and I recommend it.

Keith Steiger
(who is going through a crash course on Tcl and loving it)
"Integers are GOOD! Floating-point numbers are BAD!"

0 new messages