python - 加速有限差分模型

标签 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]

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

谢谢

罗宾

最佳答案

对于初学者来说,结构上的这一微小改变可将效率提高大约 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/

相关文章:

c - n 段求根算法的性能

c - 在 C 中是否有更好的方法求函数的 n 阶导数?

python - 在 Windows 中测试时,使用 fasttext api 的监督分类返回空数组

python - python 中 all() 的行为

python - 找到numpy数组之间差异最小的位置

numpy - 移动 Numpy 二维数组中行的位置

floating-point - 复杂的浮点类型

python - 使用 Raspberry Pi 3 B 型(和 Pi 相机)进行高速高分辨率图像捕获

python - 自动覆盖 pandas 数据框中的列名称

python - 如何使用 Python 根据动态条件分隔数据框的行