exp(x) overflow/underflow in Numpy (float64)

Numpy
Python
Author
Published

September 26, 2024

Modified

April 17, 2025

Code
import numpy as np

np.seterr(all="ignore")
print("Numpy float info:", np.finfo(float))
Numpy float info: Machine parameters for float64
---------------------------------------------------------------
precision =  15   resolution = 1.0000000000000001e-15
machep =    -52   eps =        2.2204460492503131e-16
negep =     -53   epsneg =     1.1102230246251565e-16
minexp =  -1022   tiny =       2.2250738585072014e-308
maxexp =   1024   max =        1.7976931348623157e+308
nexp =       11   min =        -max
smallest_normal = 2.2250738585072014e-308   smallest_subnormal = 4.9406564584124654e-324
---------------------------------------------------------------
Binary search
# Binary search: find the minimal integer x such that np.exp(x) is not zero
def find_minimal_exp_x():
    left = -10000
    right = 0
    while right - left > 1:
        mid = (left + right) // 2
        if np.exp(mid) == 0:
            left = mid
        else:
            right = mid
    return right


min_int = find_minimal_exp_x()


# Binary search: find the maximal integer x such that np.exp(x) is not infinity
def find_maximal_exp_x():
    left = 0
    right = 10000
    while right - left > 1:
        mid = (left + right) // 2
        if np.exp(mid) != np.inf:
            left = mid
        else:
            right = mid
    return right


max_int = find_maximal_exp_x()
print(f"np.exp({min_int - 1}) = {np.exp(min_int - 1)}")
print(f"np.exp({min_int}) = {np.exp(min_int)}")
np.exp(-746) = 0.0
np.exp(-745) = 5e-324
print(f"np.exp({max_int - 1}) = {np.exp(max_int - 1)}")
print(f"np.exp({max_int}) = {np.exp(max_int)}")
np.exp(709) = 8.218407461554972e+307
np.exp(710) = inf
Back to top

Reuse

Citation

BibTeX citation:
@online{li2024,
  author = {Li, Chengkun},
  title = {`Exp(x)` Overflow/Underflow in {Numpy} (Float64)},
  date = {2024-09-26},
  url = {https://pipme.github.io/posts/2024-09-26-Float64/index-gist.html},
  langid = {en}
}
For attribution, please cite this work as:
Li, Chengkun. 2024. “`Exp(x)` Overflow/Underflow in Numpy (Float64).” September 26, 2024. https://pipme.github.io/posts/2024-09-26-Float64/index-gist.html.