减少python中的嵌套循环

时间:2014-07-23 01:52:24

标签: python numpy scipy nested-loops

我是科学计算的新手,并试图模拟方差伽玛过程。我被迫使用两个嵌套循环,我知道它是低效的,并希望避免。对此有何帮助?

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

0 个答案:

没有答案