1

When I compare two numbers at python, even though they are exactly the same, the difference between these two numbers is not zero, but something really small (<10^(-16)).

e.g.

if A == B:
    print('We are the same')

Nothing happens. But:

if A - B < 10^(-16):
    print(A-B)

It prints the difference.

Where is the problem?

Keyu Bao
  • 11
  • 1

1 Answers1

2

in Python, the ^ operator execute an exclusive or, so 10^(-16) means 10 XOR (-16), which correctly returns -6 (which is lower than A-B).
If you wanted to execute an exponentiation, you have to write 10**(-16), and your check is now working as expected.

This means that your code should be:

if A - B < 10**(-16):
    print(A-B)

# OUTPUT: 0
Gsk
  • 2,929
  • 5
  • 22
  • 29