I have been looking around to find a general way of comparing two numerics in Python. In particular, I want to figure out whether they are the same or not.
The numeric types in Python are:
int, long, float & complex
a == b
In Python 3.5 (and in Numpy) you can use
>>> from math import isclose >>> isclose(1,1.00000000001) True >>> isclose(1,1.00001) False
The relative and absolute tolerance can be changed.
Relative tolerance can be thought of as +- a percentage between the two values:
>>> isclose(100,98.9, rel_tol=0.02) True >>> isclose(100,97.1, rel_tol=0.02) False
The absolute tolerance is a absolute value between the two values. It is the same as the test of
All numeric types of Python are support with the Python 3.5 version. (Use the
cmath version for complex)
I think longer term, this is your better bet for numerics. For older Python, just import the source. There is a version on Github.
Or, (forgoing error checking and
NaN support) you can just use:
abs(a-b) <= max( rel_tol * max(abs(a), abs(b)), abs_tol )