Skip to content Skip to sidebar Skip to footer

How To Compare A Variable Value To An Array

In Python, How can I compare two float variable values to ensure if they are within a certain tolerance of each other? For example: variable = 17.40 array = [14.40, 14.12, 45.50]

Solution 1:

From this question that you also asked. Here's a piece of code that will check if your variable is in the array(unless that's not what you meant by compare the variable value with the array elements):

TOLERANCE=10**-6defare_floats_equal(a,b):
  returnabs(a-b) <= TOLERANCE

deffloat_in_array(number, array):
  returnTruein [are_floats_equal(number, a) for a in array]

Edit. This might be a bit more efficient to do this way(though less succinct) as we only loop over the array once:

def float_in_array(number, array):
  for a in array:
    if are_floats_equal(number, a):
      returnTruereturnFalse

Post a Comment for "How To Compare A Variable Value To An Array"