How to compare a variable value to an array

◇◆丶佛笑我妖孽 提交于 2019-11-27 08:52:40

问题


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]

I need to compare the variable value with the array elements to see which one are close enough.


回答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**-6

def are_floats_equal(a,b):
  return abs(a-b) <= TOLERANCE

def float_in_array(number, array):
  return True in [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):
      return True
  return False


来源:https://stackoverflow.com/questions/15000126/how-to-compare-a-variable-value-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!