How to prevent Python from considering very close numbers equal?

Asked

Viewed 40 times

0

I made this algorithm to test how Python compares nearby numbers:

x = 2.5                                # número arbitrário que escolhi para fazer os testes
y = float(input('Insira o Y '))        #
print('X > Y = {}'.format(x > y))      # mostra se x>y
print('X = Y = {}'.format(x == y))     # mostra se x = y
print('X < Y = {}'.format(x < y))      # mostra se x < y

For y = 2.5 billion thousand thousand, for example, Python returns that X = Y.

Insira o Y 2.50000000000000001
X > Y = False
X = Y = True
X < Y = False

Process finished with exit code 0

How to make Python realize that X is smaller than Y, stopping rounding?

1 answer

1


This seems to be a precision problem of float. When running Python termninal and paste the value 2.50000000000000001, is returned 2.5.

To solve, use the class Decimal.

from decimal import Decimal

x = 2.5
y = Decimal(input('Insira o Y '))        
print('X > Y = {}'.format(x > y))      # false
print('X = Y = {}'.format(x == y))     # false
print('X < Y = {}'.format(x < y))      # true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.