Home > Net >  Numpy arange but doubling step size
Numpy arange but doubling step size

Time:02-10

I am currently looking for a way to use something similar to np.arange, but with the option of doubling the step size.
I know that np.arangecreates evenly spaced arrays and is not supposed to support variable step sizes. What I want as an output is something similar to np.array([0,1,3,7,15,31,...]).
Is there any built-in function that does this?
I have to use this very often and therefore would prefer to avoid for-loops or similar slow approaches.

CodePudding user response:

Try:

2 ** np.arange(0,10,1) - 1

CodePudding user response:

Try this answer

Numpy arange() function is directly a static step function. We can customize it a little to get the desired array np.array([0, 1, 3, 7, 15, 31, ...])

n = 10                     #number of elements
2**np.arange(0, n, 1)-1    #range function

This can also provide certain results. This code is much easier than other for loop methods.

Comparing the results

Using for loops for array creations like this is more efficient in processing than other methods

import timeit

print(timeit.timeit(f'np.array([2**i-1 for i in range(10)])', setup='import numpy as np'))
# 3.5182215999811888

print(timeit.timeit(f'np.fromiter((2**i-1 for i in range(10)), int)', setup='import numpy as np'))
# 3.74799029994756

print(timeit.timeit(f'2 ** np.arange(0,10,1) - 1', setup='import numpy as np'))
# 4.791339100105688

Hope you found the best answer for you :)

  • Related