|
2002-07-06
| ||
| 05:36 | • Closed ticket [576512ffff]: Math problem. plus 2 other changes artifact: e1b71ef9b0 user: dkf | |
|
2002-07-03
| ||
| 02:10 | • Open ticket [576512ffff]. artifact: e65fd3af66 user: dgp | |
| 02:00 | • Pending ticket [576512ffff]. artifact: ccf979802e user: msofer | |
| 01:58 | • Open ticket [576512ffff]. artifact: c44d61bf60 user: msofer | |
| 01:56 | • Pending ticket [576512ffff]. artifact: 47bac72330 user: msofer | |
|
2002-07-02
| ||
| 18:20 | • New ticket [576512ffff]. artifact: 2a56a18201 user: nobody | |
Math problem.
Closed / Invalid576512ffffffffffffffffffffffffffffffffffCreated 24 years agoUpdated 24 years ago
Descriptionplain2002-07-02 18:20:03
Using 8.2.3 (SGI), 8.3.1, or 8.3.3, (both linux)
the following behavior is observed:
% set x [expr 1.2*3.0]
3.6
% if {3.6 > $x} {puts "3.6 is greater than $x!"}
3.6 is greater than 3.6!
% puts [expr 3.6 > $x]
0
So, apparently the expr procedure evaluates differently
than the parsing of the if conditional.
I would rather not make all of my if statements like:
if {[expr 3.6 > $x] == 1} {...}
msoferplain2002-07-03 01:56:59
Logged In: YES
user_id=148712
This is because the internal representation of (1.2*3.0)
*is* larger than the internal representation of (3.6) -
floats are weird :(
Now, when you do
puts [expr 3.6 > $x]
expr will do double substitution - essentially, it builds
the string
"3.6 > $x"
with '$x' replaced by the string representation of its
value, then parses this string and finally evaluates the
expression.The roundtrip via the string rep of '$x' causes
the equality due to rounding in the float-to-string conversion.
If you do instead
puts [expr {3.6 > $x}]
preventing the conversion to string, you obtain 1. So: it is
consistent, the problem that they aren't equal is intrinsic
to the binary representation of floats. This is inherited
from C.
See http://wiki.tcl.tk/879 for more troublesome examples
with real numbers.
msofer Open ticket [576512ffff].
[History diff]2002-07-03 01:58:54
msoferplain2002-07-03 02:00:40
Logged In: YES user_id=148712 Oops: first I forget to assign to myself, then I inadvertedly change the status ...
dgpplain2002-07-03 02:10:33
Logged In: YES
user_id=80530
"So, apparently the expr procedure evaluates differently
than the parsing of the if conditional"
No, you will find that
[expr {3.6 > $x}]
always gives the same result as
if {3.6 > $x} {...}
You did not enclose the expression in
braces, so two rounds of substituion
occurred, including a translation from
double -> string -> double. Such
translations often lose precision and
change the precise floating point value.
Seeking arbitrarily precise answers involving
floating point values is a mistake in the
first place.
dkf Closed ticket [576512ffff].
[History diff]2002-07-06 05:36:55
Log in (anonymous is fine) to add a comment.