检查浮点数是否接近存储在数组中的任何浮点数 [英] Check if float is close to any float stored in array

查看:230
本文介绍了检查浮点数是否接近存储在数组中的任何浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个给定的float是否在一个给定的宽容范围内,接近浮点数组中的任何浮点。

 import numpy as np 

#我的浮动
a = 0.27
#宽容
t = 0.01
#数组浮动
arr_f = np.arange(0.05,0.75,0.008)

方法来做到这一点?例如如果一个在arr_f:但允许有差别的一些容忍?






$ p

通过allow tolerance,我的意思是:
$如果abs(a - i)<= t:
print'float a在arr_f中的容差范围内,则b $ b

 对于i中的arr_f:
'
break


解决方案

如何使用 np.isclose

 >>> np.isclose(arr_f,a,atol = 0.01).any()
True

np.isclose 比较两个元素的元素,看看这些值是否在一个给定的容差范围内(这里用关键字参数 atol )。该函数返回一个布尔数组。


I need to check if a given float is close, within a given tolerance, to any float in an array of floats.

import numpy as np

# My float
a = 0.27
# The tolerance
t = 0.01
# Array of floats
arr_f = np.arange(0.05, 0.75, 0.008)

Is there a simple way to do this? Something like if a in arr_f: but allowing for some tolerance in the difference?


Add

By "allow tolerance" I mean it in the following sense:

for i in arr_f:
    if abs(a - i) <= t:
        print 'float a is in arr_f within tolerance t'
        break

解决方案

How about using np.isclose?

>>> np.isclose(arr_f, a, atol=0.01).any()
True

np.isclose compares two objects element-wise to see if the values are within a given tolerance (here specified by the keyword argument atol). The function returns a boolean array.

这篇关于检查浮点数是否接近存储在数组中的任何浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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