Version 8 of Why does Tcl think a fraction less than one is zero?

Updated 2005-03-18 10:30:40

The short answer is that Tcl (like most comuter languages) doesn't do fractions; it only knows about integers and floating-point numbers. Hence expr doesn't "evaluate" fractions, but the way you would ask it to compute a quotient may look like as it evaluates a fraction.

[Explain idioms of "computer arithmetic".]

Sometimes, Tcl's expression handling can be a little bit unexpected to newcomers:

 % expr 1/2
 0

This is because the above code asks for integer division (this is true in many other languages too) and that (conceptually) contains a round-down-to-int of the result. (The remainder operation, %, is often useful when you're working with integer division).

 % puts "1/2 is [expr 1/2] remainder [expr 1%2]"
 1/2 is 0 remainder 1

If you really want to end up with a half, force one of the arguments to the division operation to be a floating-point value:

 % expr double(1)/2
 0.5

See expr problems with int for more on integer division and how to avoid it.


rdt : 2005-01-27 : This is a property of integers that can take on values of 0,1,2,... and therefore have no values between 0 and 1. However:

 % expr 1.0 / 2
 0.5

show the expected value. Whereas in a calculator, most math is done in floating point, in Tcl, floating point math is only performed when you explicitly say to do so.


Category Mathematics