Produce evenly spaced values on a logarithmic scale (like `np.linspace()`, but on a log scale)

Viewed 2671

I want to creat two samples, first an y sample with values in a range from 10^3 to 10^10 and another x sample with values in a range from 10^-5 to 10^10 for a logarithmic plot. I tried the following :

y = np.linspace(1e3,1e10, num = 1000)
x = np.linspace(1e-5,1e10, num = 1000) 

but it returns me a non evenly distributed sample, with only 1 value of the order of 10^-5 and many more of the order of 10^9 for x, and zero value between 10^-5 and 10^7. That is what I get for x:

 [1.00000000e-05 1.00100100e+07 2.00200200e+07 3.00300300e+07
 4.00400400e+07 5.00500501e+07 6.00600601e+07 7.00700701e+07
 8.00800801e+07 9.00900901e+07 1.00100100e+08 1.10110110e+08
 1.20120120e+08 1.30130130e+08 1.40140140e+08 1.50150150e+08
 ...

I want a sample with values evenly separated: with the same number of values for each 10^ order because I need it for a logarithmic plot. Why is linspace not working and how can I fix it ?

3 Answers

A linspace returns linearly spaced values, meaning there will be the same distance from each number to the next. logspace on the other hand creates logarithmically spaced values, which are what you are looking for. https://numpy.org/devdocs/reference/generated/numpy.logspace.html

Edit: Beware that logspace takes the exponent as start and stop values. Meaning you must write np.logspace(3, 10, num = 1000) and np.logspace(-5, 10, num = 1000)

Check out geomspace:

import numpy as np

y = np.geomspace(1e3, 1e10, num=8)

print(y)
[1.e+03 1.e+04 1.e+05 1.e+06 1.e+07 1.e+08 1.e+09 1.e+10]

You are using the wrong function for what you are trying to achieve here. You should use "logspace" for that.

y = np.logspace(3,10, num = 1000)
print (y)
Related