如何将一个变量值比较数组 [英] How to compare a variable value to an array

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

问题描述

在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.

推荐答案

从的这个问题的,你还问。这里是一片code,如果你的变量是数组中,将检查(除非这就是你的意思不是通过比较数组元素的变量值):

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆