【问题标题】:Iteration with constants and other variables with Arrays Numpy Python使用数组 Numpy Python 使用常量和其他变量进行迭代
【发布时间】:2021-05-11 15:03:39
【问题描述】:

我正在尝试修改下面的函数,以便它在下面给出预期的输出。对于第一个计算,它类似于100+ 100*-87/100 = 13 和等式NonC_Amount + Int_amount * np.cumprod(PnL / 100)。由于 -87 是 PnL 中的第一个元素,因此对于第二次计算,它将为 13 + 100*-4/100 = 9。 NonC_Amounts 值已更新。

PnL = np.array([-87., -4., -34.1, 8.5])
Int_amount = 100
NonC_Amount = 100
PnL.prod(initial=Int_amount)
NonCompounding =NonC_Amount  + Int_amount  * np.cumprod(PnL / 100)

电流输出:

[ 13, 103.48 , 98.81332,  99.8991322]

预期输出:

[ 13,  9,  -25.1,  -16.6]

【问题讨论】:

    标签: python arrays function numpy math


    【解决方案1】:

    你做错了计算。从你的描述看来你想做的事

    NonC_Amount = 100
    NonCompounding = np.zeros_like(PnL)
    for i in range(PnL.shape[0]):
        NonCompounding[i] = NonC_Amount + Int_amount * PnL[i] / 100
        NonC_Amount = NonCompounding[i]
    

    编辑:如果你希望这个操作矢量化,你可以这样做

    NonCompounding = NonC_Amount + np.cumsum(Int_amount * PnL / 100)
    

    np.cumprod() 为您提供到第 i 个元素的累积乘积。对于np.cumprod(PnL),那就是

    [-87, -87*(-4), -87*(-4)*(-34.1), etc...]
    

    它只是偶然地为您提供第一个元素的正确结果。

    【讨论】:

    • 我已经更新了这个问题,抱歉错误应该是 -16。而不是 16。如果可能的话,我会尽量避免 for 循环,因为它们速度慢且效率低。
    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    相关资源
    最近更新 更多