Skip to content
Tcl Source Code View Ticket
Login

View Ticket

facing issue with expr

Closed / Invalid50dfde221669097ea777859a00d47fb1eae03387Created 12 years agoUpdated 12 years ago
Descriptionplain2015-03-05 07:59:50
Found problem with "expr" while doing calculations 
For example : 
% expr (576.64 - 554.176) * 1.0 / 0.576
39.0
% expr int((576.64 - 554.176) * 1.0 / 0.576)
38 

How come the int for 39.0 will become 38?
dkfhtml2015-03-05 10:57:36

The issue is that the calculation isn't yielding the value that you think it is; when I try with Tcl 8.5 or 8.6 (both of which are much more careful in the rendering of floating point numbers than 8.4 and before were), I get this:

% expr (576.64 - 554.176) * 1.0 / 0.576
38.9999999999999
Binary floating point numbers (such as Tcl uses, along with many other programming languages) are fundamentally not capable of delivering perfectly accurate calculations for every value you can type in, in a way that is precisely analogous to how you can't represent the result of dividing 1 by 3 in a finite number of decimals. For more info see this classic paper.

The one interesting thing about Tcl is that we now guarantee to use the minimum number of digits to represent a number when converting from the floating point internal representation to the decimal string form, subject to the constraint that the reverse operation (string-to-IEEE-double) gives exactly the same thing. That is a non-trivial guarantee; it takes quite a lot of code in Tcl's implementation to achieve it. If you really want to use a smaller number of digits than what is properly necessary, the format command is the right approach, though you should be aware that this will do some rounding.

Log in (anonymous is fine) to add a comment.