加速有限差分模型

时间:2018-05-19 00:16:45

标签: python numpy numerical-methods

我有一个复杂的有限差分模型,它是用python编写的,使用与下面的示例代码相同的通用结构。它有两个for循环,每个迭代一个循环,然后在每个迭代中,沿x数组的每个位置循环。目前代码需要两个长时间运行(可能是由于for循环)。是否有一个简单的技术使用numpy删除第二个for循环?

以下是我使用的一般结构的简单示例。

import numpy as np

def f(x,dt, i):
   xn = (x[i-1]-x[i+1])/dt # a simple finite difference function
   return xn

x = np.linspace(1,10,10) #create initial conditions with x[0] and x[-1] boundaries
dt = 10 #time step
iterations = 100 # number of iterations

for j in range(iterations):
    for i in range(1,9): #length of x minus the boundaries
        x[i] = f(x, dt, i) #return new value for x[i]

有没有人对如何提高效率有任何想法或意见?

谢谢,

罗宾

1 个答案:

答案 0 :(得分:3)

对于初学者来说,这种结构的微小改变可以将效率提高大约15%。如果这个代码可以进一步优化但我很可能在函数内部算法,即简化数组元素操作的某种方法,我不会感到惊讶。使用发电机也可能有所帮助。

import numpy as np
import time

time0 = time.time()


def fd(x, dt, n):  # x is an array, n is the order of central diff
    for i in range(len(x)-(n+1)):
        x[i+1] = (x[i]-x[i+2])/dt # a simple finite difference function
    return x


x = np.linspace(1, 10, 10)  # create initial conditions with x[0] and x[-1] boundaries
dt = 10 # time step
iterations = 1000000 # number of iterations

for __ in range(iterations):
        x = fd(x, dt, 1)
print(x)

print('time elapsed: ', time.time() - time0)