[Tutor] Re: If elif not working in comparison
smiles at saysomething.com
Mon Apr 4 20:08:46 CEST 2005
On Monday, Apr 4, 2005, at 05:01 America/Chicago,
tutor-request at python.org wrote:
> Would I used an if else: construction to determine where the INR value
> lay and decide what precentage to increase it by?
Yes, that seems to be the right way to do that. The caveat is that
when you are using boolean tests like "if INR < 1.15:" you are using
floating point numbers that *by definition* have limited ability to
represent the numbers you type.
"1.15" is actually "1.1499999999999999", so calculation that "on paper"
would have led to a value of 1.15 will appear to be larger than the
floating point value of 1.15. When you are checking to see if your
program is running right and you find that a test like "if INR < 1.15"
doesn't work like you think it should this can lead to a lot of hair
pulling...until you remember the floating point issue. e.g. on paper,
a and b as shown below should be the same, but they aren't
>>> a=.23*5 # which equals 1.15 on paper
If one cares about what side of the boundary values get evaluated to
then either exact numbers should be used (e.g. the new decimal type of
python 2.4) or else the tests should use the round function to get both
numbers to a compatible precision for comparison (e.g. use "if
round(INR,2) < round(1.15,2):" instead of "if INR < 1.15".
It is instructive to see what the round function does to the a and b
used in the example above:
Both numbers are still floats, but they are floats that both best
represent, to 2 decimal places, their respective values.
More information about the Tutor