-1

I have two functions which give me very small numbers. I want to define a IF statements in which If two values are approximately the same print them otherwise pass

a = (x, y)
b = (h, p)
If a == b:
   print(a, b)
else:
   pass

for this we cannot use ==. How to define it to be close? Because the order of values maybe like a=7e-25, b=1.5e-26

Ma Y
  • 696
  • 8
  • 19

2 Answers2

1

You could use math.isclose().

from math import isclose
a = 1.0
b = 1.00000001
print(isclose(a, b, abs_tol=1e-8))  # -> True

[Comment update] If you want to find value of a list that is closest to some value, here's example solution

a = 7e-25
b = [1.5e-26,1.4e-26,1.3e-26,1.4e-26,1.5e-27]
print(min(b, key=lambda x: abs(a-x)))  # -> 1.5e-26
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
0

Use the numpy function isclose:

import numpy as np
a = 7e-25
b = 1.5e-26
if np.isclose(a, b):
    print(a, b)
Rob
  • 3,418
  • 1
  • 19
  • 27
  • One thing that I cannot under stand is, How I can find closest value between these `a = 7e-25 b = [1.5e-26,1.4e-26,1.3e-26,1.4e-26,1.5e-27]` it should be `1.5e-26` – Ma Y Dec 17 '19 at 09:25
  • That's a different question, feel free to ask a new question about that. – Rob Dec 17 '19 at 09:33