0

I know to give some tolerance to compare the floats. I could use,

math.isclose(0.0005, 0.0006, abs_tol = 0.0002)

And it will give True for the response.

But let's say, we have two lists

number_list_1 = [1.15679, 0.000435343, 0.009432, 10.0, 0.5678]
number_list_2 = [1.157, 0.00044, 0.0094, 10.0, 0.568]

As you can see, two lists's elements have almost identical values, but with slightly different modifications.

How can I return True value if I compare two lists?

Dong-gyun Kim
  • 411
  • 5
  • 23
  • iterate through all elements with a for loop and use `math.isclose(l1[i], l2[i], abs)`? – nicksheen Apr 19 '20 at 16:15
  • Alternatively, most `math` functions have a `numpy` equivalent. Using [`numpy.isclose`](https://numpy.org/doc/stable/reference/generated/numpy.isclose.html?highlight=isclose#numpy.isclose) would get you what you want, if you're willing to use that package. – Thomas Jager Apr 19 '20 at 16:17

2 Answers2

1

As a one liner, you can zip() the two lists, then use all()

import math
number_list_1 = [1.15679, 0.000435343, 0.009432, 10.0, 0.5678]
number_list_2 = [1.157, 0.00044, 0.0094, 10.0, 0.568]
print(all((math.isclose(n1, n2, abs_tol = 0.0002) for n1, n2 in zip(number_list_1, number_list_2))))

Or if you want something more explicit:

def is_close(n1, n2, abs_tol=0.0002):
    if len(n1) != len(n2):
        return False    
    for n1, n2 in zip(n1, n2):
        if not math.isclose(n1, n2, abs_tol=abs_tol):
            return False            
    return True
print(is_close(number_list_1, number_list_2))
Victor
  • 2,864
  • 1
  • 12
  • 20
0
import math

number_list_1 = [1.15679, 0.000435343, 0.009432, 10.0, 0.5678]
number_list_2 = [1.157, 0.00044, 0.0094, 10.0, 0.568]

for x in range(len(number_list_1)):
    for y in range(len(number_list_2)):
        print (number_list_1[x],number_list_2[y], math.isclose(x, y, abs_tol = 0.0002))