Bottom Page

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
>>>
Quote
#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

Quote
#3
'http://' + str(0.1 + 0.2) + '.com'
http://0.30000000000000004.com

You should use math.isclose.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  floating point not increasing properly rakeshpe43 4 259 Apr-30-2020, 05:37 AM
Last Post: rakeshpe43
  connecting the first point to the last point Matplotlib omar_mohsen 0 255 Jan-15-2020, 01:23 PM
Last Post: omar_mohsen
  Complex floating issue arshad 2 981 Nov-05-2019, 03:26 PM
Last Post: arshad
  finding the closest floating point number in a list Skaperen 17 1,112 Sep-19-2019, 10:39 PM
Last Post: Skaperen
  finding the next higher representable floating point value Skaperen 0 487 Sep-13-2019, 11:16 PM
Last Post: Skaperen
  Need help with arithmetic calculation rakesh561 0 431 Mar-08-2019, 09:54 PM
Last Post: rakesh561
  Subtracting values between two dictionaries/ floating point numbers FloppyPoppy 5 1,527 Mar-04-2019, 01:00 PM
Last Post: snippsat
  Conversion needed from bytearray to Floating point braveYug 1 799 May-07-2018, 12:23 PM
Last Post: snippsat
  print floating point number Regulus 19 4,696 Aug-14-2017, 02:42 PM
Last Post: nilamo

Forum Jump:


Users browsing this thread: 1 Guest(s)