Reputation: 9452
I am using the following code to find out which of the two numbers has a maximum value:
maximum = max(2.3,2.300000000001)
print maximum
But the output I get is 2.3
and not 2.300000000001
. Can anyone explain why this happens?
Upvotes: 2
Views: 237
Reputation: 148890
In your case, as said by mureinik, only print was the cause of the problem. A more direct demonstration is :
>>> a = 2.300000000001
>>> a
2.300000000001
>>> print(a)
2.3
But beware, Python uses underlying floating point of its platform and it has not an inifinite accuracy. As a rule of thumb, only 16 decimal digits are accurate:
>>> b = 2.300000000000000001
>>> b
2.3
>>> c = 2.3
>>> b == c
True
Upvotes: 1
Reputation: 1066
The Python print command truncates numbers automatically. There's some explanations in the comments above. If you want it to print the full value, try using print "%13f" % maximum
to show you the full value
Upvotes: 1
Reputation: 12058
From the doc:
14. Floating Point Arithmetic: Issues and Limitations
It’s easy to forget that the stored value is an approximation to the original decimal fraction, because of the way that floats are displayed at the interpreter prompt. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead
>>> 0.1
0.1
Answer: result you get is fine, but print
rounds it.
You can check the actual value with repr():
maximum = max(2.3,2.300000000001)
print repr(maximum)
Upvotes: 4
Reputation: 311163
Don't worry - max
isn't broken, and maximum
indeed holds 2.300000000001
. print
, however, rounds it when printing. You could use repr
to prove that:
>>> maximum = max(2.3,2.300000000001)
>>> print maximum
2.3
>>> print repr(maximum)
2.300000000001
Upvotes: 7
Reputation: 140
The "absolute or relative difference" check is implemented by code equivalent to the following Python code:(https://code.google.com/codejam/apactest/faq.html#case_1)
def IsApproximatelyEqual(x, y, epsilon):
"""Returns True iff y is within relative or absolute 'epsilon' of x.
By default, 'epsilon' is 1e-6.
"""
# Check absolute precision.
if -epsilon <= x - y <= epsilon:
return True
# Is x or y too close to zero?
if -epsilon <= x <= epsilon or -epsilon <= y <= epsilon:
return False
# Check relative precision.
return (-epsilon <= (x - y) / x <= epsilon
or -epsilon <= (x - y) / y <= epsilon)
It would be good to check this thing as well. When python comes out with output, there is some range of ignorance when dealing with real numbers.
Upvotes: 0