Why does my NumPy logspace give me an infinity array?

Viewed 543

To get a logarithmic array of 1000 until 1000000000 with 23 points I wrote this code in Python:

import numpy as np

x4 = np.logspace(start=1000, stop=1000000000, num=23, base=10)
print(x4)

The results where:

[inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf inf]

How do you solve this problem and what did I do wrong in my code?

2 Answers

np.logspace is not doing what you think it's doing. You are expecting the effect of np.geomspace:

10**np.linspace(np.log(1000), np.log10(1000000000), 23)

In fact, you are getting

10**np.linspace(1000, 1000000000, 23)

From the docs:

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).

So you probably want

np.logspace(3, 9, num=23, base=10)

Or alternatively,

np.geomspace(10**3, 10**9, 23)

The exact reason for the result can be seen with np.finfo:

>>> np.finfo(np.float_)
finfo(resolution=1e-15, min=-1.7976931348623157e+308, max=1.7976931348623157e+308, dtype=float64)

Since 10**1000 > 1.7976931348623157e+308, inf is just a signal of the expected overflow.

I think you misunderstood what logspace does. It gives you the powers, starting with base**start, which in your case is 10**1000. So in your case:

out = np.logspace(start=3, stop=9, num=23, base=10)

And test:

plt.plot(out)
plt.yscale('log')

Output:

enter image description here

Related