我有一个复杂的有限差分模型,它是用 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]
有人对我如何提高效率有任何想法或意见吗?
谢谢
罗宾
最佳答案
对于初学者来说,结构上的这一微小改变可将效率提高大约 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)
关于python - 加速有限差分模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420637/