Jay Klope
Jay Klope

Reputation: 145

Occurrences of floating point errors and how to prevent them

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?

Upvotes: 1

Views: 536

Answers (2)

U13-Forward
U13-Forward

Reputation: 71560

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

Upvotes: 1

piedra
piedra

Reputation: 1443

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.

Upvotes: 0

Related Questions