1

I have this program which calculates the total for all the values entered by the user:

result = 0
for i in range(3):
    n = float(input("Enter a value: "))
    result = result + n
print(result)

If I entered in the values, 1.2, 1.3, 1.3, the output will be correct and print a result of 3.8. However, it seems when I enter in three floating point values which are all the same, I will get a floating point error. For example, 1.2, 1.2, 1.2 will print out 3.5999999999999996.

Why does this seem to happen? Is there a way that I can prevent it?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Jay Klope
  • 135
  • 2
  • 7
  • 1
    Basically, if you need precise arithmetic don't use `float`s. Instead, use something like the [`decimal`](https://docs.python.org/3/library/decimal.html) module. – Patrick Haugh Jun 29 '18 at 01:15
  • @PatrickHaugh: `decimal` isn't exact either, though. Mostly, it's just decimal, so its imprecision lines up better with human intuition. (It also offers configurable precision and a bunch of other advanced options, but none of them make the problem of rounding go away.) – user2357112 Jun 29 '18 at 01:24
  • The term *floating point error* usually means an exception like divide by zero or arccosine of too large a number. What you are describing is not that sort of error, but an unexpected result which comes from misunderstanding what a float is. The fundamental issue is that `0.1` cannot be exactly expressed in a `float` or `double` just like `1/3` cannot be exactly expressed with decimal notation. – wallyk Jun 29 '18 at 01:50

2 Answers2

1

It doesn't work because float does a lot more decimal numbers, for more information check this: link, so you should do the below:

result = 0
for i in range(3):
    n = float(input("Enter a value: "))
    result = result + n
print('{0:.1f}'.format(result))

Output:

Enter a value: 1.2
Enter a value: 1.2
Enter a value: 1.2
3.6

Or:

result = 0
for i in range(3):
    n = float(input("Enter a value: "))
    result = result + n
print('%.1f'%result)

Output:

Enter a value: 1.1
Enter a value: 1.1
Enter a value: 1.1
3.3

decimal module:

Try this:

from decimal import Decimal
result = 0
for i in range(3):
    n = Decimal(input("Enter a value: "))
    result = result + n
print(result)

Output:

Enter a value: 2.1
Enter a value: 2.1
Enter a value: 2.1
6.3
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

That happens because the floating point numbers does not have an exact representation, for more information check this.

If precision is critical for you, you can use python decimal.

piedra
  • 1,343
  • 14
  • 13