Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
floating point arithmetic
#1
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
>>>
Reply
#2
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]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
'http://' + str(0.1 + 0.2) + '.com'
http://0.30000000000000004.com

You should use math.isclose.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Evaluating arithmetic expression with recursion. muddybucket 3 2,759 Dec-17-2021, 08:31 AM
Last Post: deanhystad
  Simple arithmetic question ebolisa 5 2,007 Dec-15-2021, 04:56 PM
Last Post: deanhystad
  Magic Method Arithmetic Operators ClownPrinceOfCrime 3 2,280 Jan-10-2021, 03:24 PM
Last Post: ndc85430
  floating point not increasing properly rakeshpe43 4 2,346 Apr-30-2020, 05:37 AM
Last Post: rakeshpe43
  connecting the first point to the last point Matplotlib omar_mohsen 0 4,524 Jan-15-2020, 01:23 PM
Last Post: omar_mohsen
  Complex floating issue arshad 2 11,768 Nov-05-2019, 03:26 PM
Last Post: arshad
  finding the closest floating point number in a list Skaperen 17 8,109 Sep-19-2019, 10:39 PM
Last Post: Skaperen
  finding the next higher representable floating point value Skaperen 0 1,916 Sep-13-2019, 11:16 PM
Last Post: Skaperen
  Need help with arithmetic calculation rakesh561 0 1,866 Mar-08-2019, 09:54 PM
Last Post: rakesh561
  Subtracting values between two dictionaries/ floating point numbers FloppyPoppy 5 5,827 Mar-04-2019, 01:00 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020