Ma Y
Ma Y

Reputation: 706

Writing a for loop with very big or very small numbers in python

How to write a for loop that values varies from 1e-70 to 1e-10 with arbitrary step like 0.000001.

for i in np.arange (1e-70, 1e-10):

or writing a for loop for big values as 1e20 to 1e33

I didint know what should I search to find the relevant answer.

Upvotes: 3

Views: 948

Answers (2)

Taras Khalymon
Taras Khalymon

Reputation: 614

You should specify a step in np.arange() like this:

for i in np.aragne(1e-70, 1e-10, 1e-20):

But note, if your step is bigger than values range, you'll get only a start of your range. So in case np.arange(1e-70, 1e-10, step=1e-6) you'll have only one iteration with i=1e-70.

Or if you want to have N equally spaced numbers, you can use np.linspace():

for i in np.linspace(1e-70, 1e-10, 1000): # 1000 numbers in [1e-70, 1e-10]

P.S. Looking at your question, it seem's that you want to get a sequence like [1e-70, 1e-69, 1e-68, ...] instead of [1e-70, 1e-70+step, 1e-70+2*step, ...]. In it is so, you can do it like this:

for i in np.logspace(-70, -10, 61):

Upvotes: 2

neko
neko

Reputation: 389

If your objective is to get[1e-70, 1e-69, 1e-68,...], why not use np.logspace?

np.logspace(-70, -10, 61)

returns exactly that.

Upvotes: 3

Related Questions