I am generating this series of numbers using a for loop
[1.e-03 1.e-04 1.e-05 1.e-06 1.e-07 1.e-08 1.e-09 1.e-10 1.e-11 1.e-12]
This is the for loop:
alphas = np.zeros(10)
alphas[0] = 0.001
for i in range(1,10):
alphas[i] = alphas[i-1] * 0.1
My heart of hearts tells me this is not "pythonic", but my brain can't come up a list comprehension to build this.
I've tried numpy.linspace
, arange
, etc, but can't quite land where I need to. I wrote the for loop in 60 seconds, but am trying every time I write a for loop to think about how I could do it with a list comprehension.
CodePudding user response:
Think about what you want the range on: it's powers of 10
[10**x for x in range(-3, -13, -1)]
Or
10.0**np.arange(-3, -13, -1)
# or
10.0**-np.arange(3, 13)
The numpy example uses a float 10.0 because in numpy,
Integers to negative integer powers are not allowed
CodePudding user response:
Very similar answer to @Pranav, but personally I always find ascending ranges easier to read:
>>> [10 ** -k for k in range(3, 13)]
[0.001, 0.0001, 1e-05, 1e-06, 1e-07, 1e-08, 1e-09, 1e-10, 1e-11, 1e-12]
>>> np.power(10., -np.arange(3, 13))
array([1.e-03, 1.e-04, 1.e-05, 1.e-06, 1.e-07, 1.e-08, 1.e-09, 1.e-10,
1.e-11, 1.e-12])