pceccon
pceccon

Reputation: 9844

Creating numpy array with different steps

I would like to create an array like the following:

# 0 | 4 | 8 | 16 | 32

In which, each element except the first, is the double of the previous one. I can create this smaller through an iteration and so on.

However, as Python provides a lot of one-liner functions, I was wondering if there is one that allows me to do that.

Upvotes: 3

Views: 3169

Answers (3)

Cory Kramer
Cory Kramer

Reputation: 117876

import numpy as np

You could use a list comprehension to evaluate your power function (2^n in this case), then generate a numpy.array from that.

>>> np.array([0] + [2**i for i in range(2, 10)])
array([  0,   4,   8,  16,  32,  64, 128, 256, 512])

Upvotes: 2

lmjohns3
lmjohns3

Reputation: 7592

You can use numpy.logspace to get log-spaced ranges. Use the base=N keyword argument to set the base of the exponent:

In [27]: np.logspace(0, 10, 11, base=2).astype(int)
Out[27]: array([   1,    2,    4,    8,   16,   32,   64,  128,  256,  512, 1024])

I like this method because the "logspace" function name makes it clear that I'm going for a range with log (as opposed to linear) spacing.

Upvotes: 2

mdurant
mdurant

Reputation: 28683

Could be one line, but this is more explicit:

x = np.multiply.accumulate( np.ones( 10 )*2)
x[0] = 0

OR

x  = 2**np.arange(1,10)
x[0] = 0

Upvotes: 6

Related Questions