Python Forum

Full Version: floating point arithmetic
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a beginner at Python. How does one get Python to be more accurate when doing floating point arithmetic?

For example, in this very simple code:

def AddTwoValues(x, y):
    return(x + y)


firstValue = 8.9
secondValue = 3.14 
result = AddTwoValues(firstValue, secondValue)
print(result)

correctValue = 12.04

if correctValue == result:
    print(result, " equals ", correctValue)
else:
    print(result, " does not equal ", correctValue)
Python returns:

>
12.040000000000001
12.040000000000001 does not equal 12.04
>>>
You don't get more accurate with floating point arithmetic. It is just inherently inaccurate. You can use the decimal or fractions modules if you want accurate calculations with non-whole values. Another thing you can do is change your comparisons to account for inaccuracies:

epsilon = 0.0000001
result = 8.9 + 3.14
correct_value = 12.04
if abs(result - correct_value) < epsilon:
    print('Close enough.')
else:
    print('Not close enough.')
[/python]
'http://' + str(0.1 + 0.2) + '.com'
http://0.30000000000000004.com

You should use math.isclose.