I'd like to implement a geometric progression using Python / Pandas / Numpy.
Here is what I did:
N = 10
n0 = 0
n_array = np.arange(n0, n0 + N, 1)
u = pd.Series(index = n_array)
un0 = 1
u[n0] = un0
for n in u.index[1::]:
#u[n] = u[n-1] + 1.2 # arithmetic progression
u[n] = u[n-1] * 1.2 # geometric progression
print(u)
I get:
0 1.000000
1 1.200000
2 1.440000
3 1.728000
4 2.073600
5 2.488320
6 2.985984
7 3.583181
8 4.299817
9 5.159780
dtype: float64
I wonder how I could avoid to use this for loop.
I had a look at https://fr.wikipedia.org/wiki/Suite_g%C3%A9om%C3%A9trique and found that u_n can be expressed as: u_n = u_{n_0} * q^{n-n_0}
So I did that
n0 = 0
N = 10
n_array = np.arange(n0, n0 + N, 1)
un0 = 1
q = 1.2
u = pd.Series(map(lambda n: un0 * q ** (n - n0), n_array), index = n_array)
That's ok... but I'm looking for a way to define it in a recurrent way like
u_n0 = 1
u_n = u_{n-1} * 1.2
But I don't see how to do it using Python / Pandas / Numpy... I wonder if it's possible.
Another possibility, that is probably more computationally efficient than using exponentiation:
>>> N, un0, q = 10, 1, 1.2
>>> u = np.empty((N,))
>>> u[0] = un0
>>> u[1:] = q
>>> np.cumprod(u)
array([ 1. , 1.2 , 1.44 , 1.728 , 2.0736 ,
2.48832 , 2.985984 , 3.5831808 , 4.29981696, 5.15978035])
Use numpy.logspace
>>> import numpy
>>> N=10
>>> u=numpy.logspace(0,N,num=N, base=1.2, endpoint=False)
>>> print u
[ 1. 1.2 1.44 1.728 2.0736 2.48832
2.985984 3.5831808 4.29981696 5.15978035]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With