问题描述
我想使用 Python 在连续时间内模拟某个随机过程的路径。我写了下面的函数来模拟它(np
当然指的是numpy
):
def simulate_V(v0,psi,theta,dt,xsi,sample,diff = False):
_,dB = independent_brownian(dt,1,diff = True)
path_lenght = len(dB) + 1
V = np.zeros(path_lenght)
dV = np.zeros(len(dB))
V[0] = v0
for i in range(len(dV)):
dV[i] = psi * (theta - V[i]) * dt + xsi * np.sqrt(V[i]) * dB[i]
V[i+1] = V[i] + dV[i]
if diff == True:
return(V,dV)
else:
return(V)
independent_brownian
函数只是为标准布朗运动创建路径。为了完整起见,这里是:
def independent_brownian(dt,n,diff=False):
'''
Creates paths of independent Brownian motions. Returns increments if diff == True.
--------
dt -> variance of increments\\
n -> how many paths\\
sample -> length of sampled path\\
diff -> return increments or not?\\
Returns a (n,sample)-shaped array with the paths
'''
increments = np.sqrt(dt) * np.random.randn(n,sample)
paths = np.cumsum(increments,axis=1)
b = np.zeros((n,sample + 1))
b[:,1:] = paths
if n==1:
b = b.flatten()
increments = increments.flatten()
if diff == True:
return(b,increments)
else:
return(b)
碰巧我的模型背后的数学暗示过程 $V_t$(在上面的代码中由其离散化 V
表示)必须是正的。但是,可能是数组 dB
包含绝对值很大的负元素的情况。我想自动化以下“选择”程序:
- 尝试遵循
simulate_V
中描述的循环; - 在某个时刻,如果
V[i]
低于零,则中断该过程,对另一个序列dB
进行采样并重新开始; - 当
V
的所有元素都为正时停止;
自动化此过程的好方法是什么?现在,我明白,如果 V[i]
低于零,我会在 numpy 中得到一个 nan
,但它不会抛出任何错误或停止进程。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)