Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

python - Check if float is close to any float stored in array

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 which is the absolute difference between two elements). The function returns a boolean array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...