IsClose() in python


This post tries to answer whether given numbers are comparatively close to each other. This can help if you are using Python for data science or in the area of computer vision doing computing with images. A quick stack-overflow search shows discussion around finding “nearest” value from a set of given values for any given number [1] [2] [3]. However, there could be a need to limit how much further the nearest number could be. I’d call this limit a “threshold”.

Quite a few times, in my Python (esp. in computer vision related) programming I come across scenarios when I want to tell if the two numbers are close to each other. Some might ask, “Well define close!?” or “How close?”, well … comparatively close.

Now question becomes, does the precision of the number has anything do to with it? To answer that question, let’s take a set of numbers [0.919, 0.91, 0.92]. If you were to go by precision of 2 decimal points, 0.91 and 0.92 are close. In fact, for this specific number set that is false. The difference, specifically relative difference between the given numbers matters.

Let’s consider following number sets:

  • 0.90456, 0.91874, 0.89975
  • 1.0, 0.99897, 0.99015

So as you can probably tell from eye gaze observation, in the first example, we see that 0.90456 and 0.89975 are closer, as compared to 0.91874 and in the second example, first two numbers are relatively closer. Here is my implementation as follows:

def IsClose(value, target, threshold=0.02):
result = (value / target)
result = ((1 - threshold) <= result) and (result <= (1 + threshold))
return result
view raw IsClose.py hosted with ❤ by GitHub

As you can probably tell, this has been inspired from numpy.isclose() function [4].

Output:

Default threshold

>>> IsClose(0.99897, 1.0)
True
>>> IsClose(0.99897, 0.99015)
True

Custom threshold

>>> IsClose(0.90456, 0.89975,0.006)
True
>>> IsClose(0.90456, 0.91874, 0.006)
False

References:
  1. from list of integers, get number closest to a given value
  2. Find nearest value in numpy array
  3. Finding k closest numbers to a given number
  4. numpy.isclose

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s