Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Producing a geometric sequence using NumPy

I’m trying to produce a geometric sequence, something similar to 1, 2, 4, 8…

I have the following code:

import numpy as np

lower_price = 1
upper_price = 2
total_grids = 10

grid_box = np.linspace(lower_price , upper_price, total_grids, retstep=True)

print(grid_box)

This outputs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(array([1.        , 1.11111111, 1.22222222, 1.33333333, 1.44444444,
       1.55555556, 1.66666667, 1.77777778, 1.88888889, 2.        ]), 0.1111111111111111)

This code creates an arithmetic, rather than a geometric sequence. How can I fix this code to produce the latter as opposed to the former?

>Solution :

You’re looking for np.logspace, not np.linspace:

For example,

# Lower bound is 2**0 == 1
# Upper bound is 2**10 == 1024
np.logspace(0, 10, 10, base=2)

outputs:

[1.00000000e+00 2.16011948e+00 4.66611616e+00 1.00793684e+01
 2.17726400e+01 4.70315038e+01 1.01593667e+02 2.19454460e+02
 4.74047853e+02 1.02400000e+03]

If you’re trying to get 10 values between 1 and 2, use:

# Lower bound is 2**0 == 1
# Upper bound is 2**1 == 2
np.logspace(0, 1, 10, base=2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading