使用Python/Pandas/Numpy的几何级数(无循环,使用递归)

2024-09-30 12:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python/Pandas/Numpy实现一个几何级数。在

以下是我所做的:

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)

我得到:

^{pr2}$

我想知道如何避免使用这个for循环。在

我看了看 https://fr.wikipedia.org/wiki/Suite_g%C3%A9om%C3%A9trique 并发现uün可以表示为:uüun=u{n_0}*q^{n-n}0}

所以我就这么做了

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)

没关系。。。但我正在寻找一种方法来定义它

u_n0 = 1
u_n = u_{n-1} * 1.2

但是我不知道如何使用Python/Pandas/Numpy来实现。。。我想知道是否可能。在


Tags: innumpypandasforindexnparithmeticarray
3条回答

以下是我在《熊猫》系列中的表现:

N = 10
n0 = 0
n_array = np.arange(n0, n0 + N, 1)
u = pd.Series(index = n_array)
u[n0] = 1
q = 1.2
# option 1:
u = pd.Series(u[n0]*q**(u.index.values - n0), index = n_array)
# or option 2 with cumprod
u[1:] = q
u = u.cumprod()

使用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]

另一种可能性是,这可能比使用指数运算更有效:

>>> 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])

相关问题 更多 >

    热门问题