减少python中的嵌套循环

2024-09-29 23:18:53 发布

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

我对科学计算和尝试模拟方差伽马过程是新手。我被迫使用两个嵌套循环,我知道这是低效的,并希望避免。有什么帮助吗?在

 V_0=100
 r=0.02
 q=0
 sigma=0.2
 nu=0.7
 theta=0.06

 N=1000
 M=1000
 T=1

 dt=T/M
 omega=np.log(1-((sigma**2)*nu)/2-theta*nu)/nu

 VG=np.zeros([N,M])
 V_t=np.zeros([N,M])
 Time=np.arange(0,T,dt)

 t1 = time.time()
 VG[:,0]=0
 V_t[:,0]=V_0

 #this is the loop I would like to get rid off

 for j in xrange(0,N):
    for i in xrange(0,M-1):
       VG[j,i+1] = VG[j,i] + theta*gammavariate(dt/nu,nu) + sigma*np.sqrt(gammavariate(dt/nu,nu))*standard_normal()
       V_t[j,i+1]= V_0*np.exp((r-q+omega)*dt+VG[j,i+1])

 for i in xrange(0,5):
     plt.plot(Time,V_t[i])

 t2 = time.time()
 print t2 - t1

 plt.show()

Tags: infortimenpdtzerossigmanu

热门问题