Description
Feature or enhancement
Proposal:
The default way to set float variables to infinity is float('inf')
, which is a very slow function call.
Another popular way is math.inf
, which is much faster (7.5 times), but still involves an import and an internal LOAD_ATTR.
Using a number > FLOAT64_MAX is fastest way (and not documented), a=1e999
(>1.8e+308).
1e999 == float('inf')
is True. (factor 2 speed improvement if assignment a=
is taken out.
IEEE 754-1985 specifies: 1.0/0.0==inf, 0.0/0.0=nan, but Python gives "ZeroDivisionError: float division by zero".
Summary: the fastest way is neither documented nor identical (each user could choose other large numbers, making code less comparable. And even Python is investing in performance, some low hanging fruits are ignored.
My suggestion: creating a zero-cost official number (or shortcut) for +inf, -inf, nan (e.g. following IEEE-spec like C). Python-interpreter simplifies (2.0+1.0) to 3.0 (at compile time), but 1.0/0.0 becomes a real BINARY_OP(/) at runtime (and causes a crash).
And mention the fastest way in documentaion.
A comparision script is below.
echo "Speed Test Float 2024 (Windows+Linux)"
echo off
python --version
echo "float('inf') is slow .."
python -m timeit -s "import math;a=1.1" "a=float('inf')"
echo "math.inf is faster .."
python -m timeit -s "import math;a=1.1" "a=math.inf"
echo "1e999=inf is fastest .."
python -m timeit -s "import math;a=1.1" "a=1e999"
python -c "print('inf =', 1e999, 1e999==float('inf'))"
python -c "# print('inf =', 1.0/0.0) # crash vs. IEEE 754-1985 : 1.0/0.0==inf, 0.0/0.0=NaN"
echo "Test done."
pause
exit
Python 3.11.9
"float('inf') is slow .."
2000000 loops, best of 5: 182 nsec per loop
"math.inf is faster .."
10000000 loops, best of 5: 24.3 nsec per loop
"1e999=inf is fastest .."
20000000 loops, best of 5: 11.9 nsec per loop
inf = inf True
"Test done."
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere