Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a logarithmic spaced array in Python?

Tags:

python

arrays

I want to create a array that starts from 10^(-2) and goes to 10^5 with logarithmic spaced, like this:

levels = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08. 0.09, 0.1, 0.2,..., 10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,200.,300.,400.,500.,600.,700.,800.,900.,1000.,2000.,3000.,4000.,5000.,6000.,7000.,8000.,9000.,10000.,20000.,30000., ..., 100000.]

Is there a way to create it without write down every single number?

I noticed there is a function in NumPy called logspace, but it doesn't work for me because when I write:

levels = np.logspace(-2., 5., num=63)

It returns me an array equally spaced, not with a logarithmic increasing.

like image 740
Paula Lima Avatar asked Sep 18 '18 15:09

Paula Lima


1 Answers

You can use an outer product to get the desired output. You just have to append 100000 at the end in the answer as answer = np.append(answer, 100000) as pointed out by @Matt Messersmith

Explanation

Create a range of values on a logarithmic scale from 0.01 to 10000

[1.e-02 1.e-01 1.e+00 1.e+01 1.e+02 1.e+03 1.e+04]

and then create a multiplier array

[1 2 3 4 5 6 7 8 9]

Finally, take the outer product to generate your desired range of values.

a1 = np.logspace(-2, 4, 7)
# a1 = 10.**(np.arange(-2, 5)) Alternative suggested by @DSM in the comments
a2 = np.arange(1,10,1)
answer = np.outer(a1, a2).flatten()

Output

[1.e-02 2.e-02 3.e-02 4.e-02 5.e-02 6.e-02 7.e-02 8.e-02 9.e-02 1.e-01 2.e-01 3.e-01 4.e-01 5.e-01 6.e-01 7.e-01 8.e-01 9.e-01 1.e+00 2.e+00 3.e+00 4.e+00 5.e+00 6.e+00 7.e+00 8.e+00 9.e+00 1.e+01 2.e+01 3.e+01 4.e+01 5.e+01 6.e+01 7.e+01 8.e+01 9.e+01 1.e+02 2.e+02 3.e+02 4.e+02 5.e+02 6.e+02 7.e+02 8.e+02 9.e+02 1.e+03 2.e+03 3.e+03 4.e+03 5.e+03 6.e+03 7.e+03 8.e+03 9.e+03 1.e+04 2.e+04 3.e+04 4.e+04 5.e+04 6.e+04 7.e+04 8.e+04 9.e+04]
like image 191
Sheldore Avatar answered Oct 21 '22 10:10

Sheldore