Search code examples
pythonintegercomparison-operators

Make the biggest number in python


I'm looking for a Python object which is guaranteed to compare greater than any given int. It should be portable, platform-independent and work on both Python 2.7+ and 3.x.

For example:

x = float('inf')
while True:
    n = next(my_gen)
    if my_calc(n):
        x = min(n, x)
        if my_cond(x):
            break

Here I've used float('inf') for this purpose because it seems to behave correctly. But this feels dirty, because I think it relies on some underlying float specification and I don't know whether that's going to be platform dependent or break in unexpected ways.

I'm aware that I could create my own class and define the comparison operators, but I thought there might be an existing built-in way.

Is it safe to use float('inf') like this? Is there a less ugly way of creating this "biggest integer"?


Solution

  • float('inf') is guaranteed to test as larger than any number, including integers. This is not platform specific.

    From the floatobject.c source code:

    else if (!Py_IS_FINITE(i)) {
        if (PyInt_Check(w) || PyLong_Check(w))
            /* If i is an infinity, its magnitude exceeds any
             * finite integer, so it doesn't matter which int we
             * compare i with.  If i is a NaN, similarly.
             */
            j = 0.0;
    

    Python integers themselves are only bounded by memory, so using 10 ** 3000 is not going to be big enough, probably.

    float('inf') is always available; Python will handle underlying platform specifics for you to make this so.