2

I have two numbers -

3.125000 Mbytes and 2.954880 Mbytes.

I want to compare them and it should return True since they are almost 3Mbytes. How can I do so in Python3.

I tried doing math.isclose(3.125000,2.954880, abs_tol=0.1).

However, this returns False. I really don't understand how to put tolerance here.

math.isclose(3.125000,2.954880,  abs_tol=0.1). 

https://docs.python.org/3/library/math.html

math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

I am using Python 3.5.2.

The expected result is True. The actual result is False.

1
  • The difference is more than 0.1, so not "close" enough. Commented Mar 28, 2019 at 8:47

2 Answers 2

4

Your absolute tolerance is set to 0.1, so the difference would have to be less than 0.1 to consider them equal; 3.125000 - 2.954880 is (rounded) 0.17012, which is too big.

If you want them to be considered close, increase your tolerance a bit, e.g.:

math.isclose(3.125000, 2.954880, abs_tol=0.2)

which returns True as you expect.

Sign up to request clarification or add additional context in comments.

Comments

2

The function math.isclose is really meant for dealing with floating-point imprecisions. You can use it for this, but you need to tune it appropriately: the numbers in your example are more than 0.1 apart.

If you're not worried about floating-point imprecisions, the better way to compare them is the obvious one:

def equivalent(a, b):
    return abs(a-b) < 0.1

2 Comments

It uses both, but it's considered "close" if either threshold is met; passing abs_tol of 0.1 is roughly equivalent to what you wrote, but would also allow truly huge numbers with small relative differences to be considered close as well.
@ShadowRanger Yep, realized my mistake when I saw your answer. Edited so as not to mislead OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.