gerrit
gerrit

Reputation: 26515

Why does `math.ldexp` raise OverflowError for exponent>1024, but not for exponent<-1073?

math.ldexp(0.5, 1025) results in OverflowError. Numpy's equivalent function returns inf. On the other end, however, math.ldexp(0.5, -1074) does not raise an exception, but rather returns 0.0, as illustrated below:

In [275]: math.ldexp(0.5, 1024)
Out[275]: 8.98846567431158e+307

In [276]: math.ldexp(0.5, 1025)
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-276-ce1573e0249b> in <module>()
----> 1 math.ldexp(0.5, 1025)

OverflowError: math range error

In [277]: math.ldexp(0.5, -1073)
Out[277]: 5e-324

In [278]: math.ldexp(0.5, -1074)
Out[278]: 0.0

Why does Python raiso an OverflowError when the exponent is too large, but not when it is too small? Is there a valid reason, or should this be considered a bug?

Upvotes: 0

Views: 53

Answers (1)

Christopher Shroba
Christopher Shroba

Reputation: 7574

IEEE floating point arithmetic is known to have some degree of imprecision. 0.0 is a value which is very close to math.ldexp(0.5, -1074). However, there is no valid way of expressing a value that is close to math.ldexp(0.5, 1025), so I would assume that's why it raises an Exception.

Upvotes: 3

Related Questions