user7400644
user7400644

Reputation: 37

What is the simplest way to check if two numbers are close to being equal?

Here's my code:

variable1=201
variable2=202
if variable1==variable2:
    print ("done")

I want my code to recognise that the numbers are close to being equal and print "done". I want the computer to print "done" if the difference between the two numbers is less than or equal to 5.

Upvotes: 2

Views: 6478

Answers (2)

Wright
Wright

Reputation: 3424

Could use:

variable1 = 201
variable2 = 202
if variable1 - variable2 in range(-5,5):
    print('Done')

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160417

You can either subtract them and evaluate their absolute value as Patrick suggests or you could utilize isclose from the math module with a similar effect, if you're using Python >= 3.5.

Though suggested, isclose is probably not the best if you're starting out since the tolerance arguments might confuse, so I'd go with abs(variable1 - variable2) <= 5 if I were you.

Upvotes: 4

Related Questions