Python Tips- Maximum Value float('inf')
Fei
Posted on February 2, 2024
In Python, there are two types: 'int' and 'float'. It's important to note that in Python 3, integers (int) have no maximum limit.
Here is a question: what is the maximum value in Python?
For the float, we can use sys.float_info
to check the details.
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
>>> print(sys.float_info.max)
1.7976931348623157e+308
The float value range
is
-1.7976931348623157e+308 <= f <= 1.7976931348623157e+308
Also, we can declare the max value in float
>>> a = float('inf')
>>> a
inf
>>> import math
>>> math.isinf(a)
True
>>>
>>> b = math.inf
>>> math.isinf(b)
True
We can compare 'inf' and float_info.max
>>> a > sys.float_info.max
True
How about the max value of 'int'? It is a 64 bit value.
>>> sys.maxsize
9223372036854775807
>>>
>>>
>>> print(sys.maxsize == 2**63 - 1)
True
But sys.maxsize
is not the max int value, you can declare a value
>>> b = 10**309
>>> type(b)
<class 'int'>
>>> b>sys.float_info.max
True
>>> b>sys.maxsize
True
>>> b > float('inf')
False
So, if you want to know why the Integer (int) has no max limit in Python
, you need read the source code, the int object is with variable size.
typedef struct _longobject PyLongObject;
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
#define PyObject_VAR_HEAD PyVarObject ob_base;
typedef struct {
PyObject ob_base;
Py_ssize_t ob_size; /* Number of items in variable part */
} PyVarObject;
typedef struct _object {
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
} PyObject;
Please refer to [6] to read the source code in C~
In summary, we can use float('inf')
as the max value in Python. For the float, we max value is sys.float_info.max
. for the integer, we can use the value sys.maxsize
. But Integer (int) has no max limit in Python 3, from the source code in C language, the int object is defined variable size
, that is why it has no max limit. Actually, the maximum integer value depends on the memory size, you can try~
Reference
[1.Maximum and minimum float values in Python]
https://note.nkmk.me/en/python-sys-float-info-max-min/
[2.Integer (int) has no max limit in Python 3]
https://note.nkmk.me/en/python-int-max-value/
[3.numeric-types-int-float-complex]
https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
[4.Int object source code ]
https://fasionchan.com/python-source/builting-object/int/
[5.Int object]
https://juejin.cn/post/7209612932367597623
[6.Python source code]
https://github.com/python/cpython/blob/v3.7.0/Objects/longobject.c#L3
Posted on February 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.