Python/Numpy:numpy.apply_along_axis 传递错误的 kwargs(任何参数)

问题描述 投票:0回答:1

我正在尝试为基于 Ito 过程的随机微分方程 (SDE) 制作简单的模拟器。为此,我尝试制作一个 1D 模拟器,如下所示:

def sde_euler_1(t0: float, x0: float, T: float, M: int, a, b):
    t = np.zeros(shape=M+1)
    t[0] = t0
    x = np.zeros(shape=(M+1))
    x[0] = x0
    dt = T / M

    for j in range(M):
        t[j+1] = t[j] + dt
        dW = np.random.normal(loc=0, scale=1.0, size=1)
        x[j+1] = x[j] + a(t[j], x[j]) * dt + b(t[j], x[j]) * dW * np.sqrt(dt)

    return x

它按预期工作。其中

a
b
是函数,如下面的
__main__
函数所示,其中指定它们是为了模拟几何布朗运动 (GBM)。

然而,SDE 的模拟有很多种不同的方法,通常需要重复模拟 N 次以进行蒙特卡洛积分(估计)。因此,我尝试创建一个函数,为此使用

numpy.apply_along_axis
。它是这样定义的

def mc_sim(t0: float, x0: float, T: float, M: int, N: int, a, b, sde_method, seed: int = 0):
    if seed > 0:
        np.random.seed(seed=seed)
    x = np.zeros(shape=(M+1, N))
    x = np.apply_along_axis(func1d=sde_method, axis=1, arr=x,
                            t0=t0, x0=x0, T=T, M=M, a=a, b=b)

    return x

我的问题是,当我运行下面的代码(

__main__
-函数)时,我得到以下错误:

TypeError: sde_euler_1() 得到参数 't0' 的多个值

在我看来,我已经完全传递了函数中使用的 6 个参数,但仍然出现错误。这是我的代码包含在

if __name__ == "__main__":    
    def a(t, x):
        return 0.07 * x

    def b(t, x):
        return 0.2 * x

    t0 = 0.0
    x0 = 100
    T = 5.0
    N = 10
    M = 250
    seed = 1

    t = np.linspace(start=t0, stop=T, num=M+1)
    y = mc_sim(t0=t0, x0=x0, T=T, M=M, N=N, a=a, b=b, sde_method=sde_euler_1, seed=seed)
    plt.plot(t, y)
    plt.show()
python numpy arguments typeerror keyword-argument
1个回答
0
投票

Python 不是类型安全的,所以在函数中显式定义一个类型纯粹是为了参考。考虑到这一点,由于错误直接与

t0
有关,请尝试将其定义为 0 而不是 0.0.

看看这是否解决了您的问题,或提供了不同的错误。

© www.soinside.com 2019 - 2024. All rights reserved.