如何将变量值与数组进行比较

如何将变量值与数组进行比较

本文介绍了如何将变量值与数组进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,如何比较两个浮点变量值以确保它们是否在彼此的特定容差范围内?

In Python, How can I compare two float variable values to ensure if they are within a certain tolerance of each other?

例如:

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.

推荐答案

来自 这个问题 你也问过.这是一段代码,用于检查您的变量是否在数组中(除非将变量值与数组元素进行比较不是您的意思):

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

这篇关于如何将变量值与数组进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 02:53