Keyu Bao
Keyu Bao

Reputation: 11

Diffrence of two same values is not zero

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?

Upvotes: 1

Views: 376

Answers (1)

Gsk
Gsk

Reputation: 2945

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

Upvotes: 2

Related Questions