denvar denvar - 10 months ago 38
Python Question

General way of comparing numerics in Python

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

For example, I can compare 2 integers (a type of numeric) by simply saying:

a == b

For floats, we have to be more careful due to rounding precision, but I can compare them within some tolerance.


We get 2 general numerics
: How do we compare them? I was thinking of casting both to complex (which would then have a 0 imaginary part if the type is, say,
) and compare in that domain?

Answer Source

In Python 3.5 (and in Numpy) you can use isclose

Read the PEP 485 that describes it, Python 3.5 math library listing and numpy.isclose for more. The numpy version works in all versions of Python that numpy is supported.


>>> from math import isclose
>>> isclose(1,1.00000000001)
>>> isclose(1,1.00001)

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)
>>> isclose(100,97.1, rel_tol=0.02)

The absolute tolerance is a absolute value between the two values. It is the same as the test of abs(a-b)<=tolerance

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 inf and NaN support) you can just use:

abs(a-b) <= max( rel_tol * max(abs(a), abs(b)), abs_tol )