【发布时间】:2015-06-11 16:29:44
【问题描述】:
我有以下代码使用公式逼近函数f() 的二阶导数:
我想比较两种不同的方法;使用循环和矩阵向量乘积,希望表明numpy 版本更快:
def get_derivative_loop(X):
DDF = []
for i in range(1,len(X)-1):
DDF.append((f(X[i-1]) - 2*f(X[i]) + f(X[i+1]))/(h**2))
return DDF
def get_derivative_matrix(X):
A = (np.diag(np.ones(m)) +
np.diag(-2*np.ones(m-1), 1) +
np.diag(np.ones(m-2), 2))/(h**2)
return np.dot(A[0:m-2], f(X))
正如预期的那样,构建矩阵A 会消耗大量时间。在numpy中构造三对角矩阵是否有更好的解决方案?
分析这两个函数会产生:
Total time: 0.003942 s
File: diff.py
Function: get_derivative_matrix at line 17
Line # Hits Time Per Hit % Time Line Contents
==============================================================
17 @profile
18 def get_derivative_matrix(X):
19 1 3584 3584.0 90.9 A = (np.diag(np.ones(m)) + np.diag(-2*np.ones(m-1), 1) + np.diag(np.ones(m-2), 2))/(h**2)
20 1 358 358.0 9.1 return np.dot(A[0:m-2], f(X))
Total time: 0.004111 s
File: diff.py
Function: get_derivative_loop at line 22
Line # Hits Time Per Hit % Time Line Contents
==============================================================
22 @profile
23 def get_derivative_loop(X):
24 1 1 1.0 0.0 DDF = []
25 499 188 0.4 4.6 for i in range(1, len(X)-1):
26 498 3921 7.9 95.4 DDF.append((f(X[i-1]) - 2*f(X[i]) + f(X[i+1]))/(h**2))
27
28 1 1 1.0 0.0 return DDF
A = (np.diag(np.ones(m)) +
np.diag(-2*np.ones(m-1), 1) +
np.diag(np.ones(m-2), 2))/(h**2)
return np.dot(A[0:m-2], f(X))
编辑
虽然初始化只进行一次是正确的,所以不需要优化,但是我发现想出一种很好且快速的方法来设置该矩阵是很有趣的。
这是使用Divakar 方法的配置文件结果
Timer unit: 1e-06 s
Total time: 0.006923 s
File: diff.py
Function: get_derivative_matrix_divakar at line 19
Line # Hits Time Per Hit % Time Line Contents
==============================================================
19 @profile
20 def get_derivative_matrix_divakar(X):
21
22 # Setup output array, equivalent to A
23 1 48 48.0 0.7 out = np.zeros((m, 3+m-2))
24
25 # Setup the triplets in each row as [1,-2,1]
26 1 1485 1485.0 21.5 out[:, 0:3] = 1
27 1 22 22.0 0.3 out[:, 1] = -2
28
29 # Slice and perform matrix-multiplication
30 1 5368 5368.0 77.5 return np.dot(out.ravel()[:m*(m-2)].reshape(m-2, -1)/(h**2), f(X))
Total time: 0.019717 s
File: diff.py
Function: get_derivative_matrix at line 45
Line # Hits Time Per Hit % Time Line Contents
==============================================================
45 @profile
46 def get_derivative_matrix(X):
47 1 18813 18813.0 95.4 A = (np.diag(np.ones(m)) + np.diag(-2*np.ones(m-1), 1) + np.diag(np.ones(m-2), 2))/(h**2)
48 1 904 904.0 4.6 return np.dot(A[0:m-2], f(X))
Total time: 0.000108 s
File: diff.py
Function: get_derivative_slice at line 41
Line # Hits Time Per Hit % Time Line Contents
==============================================================
41 @profile
42 def get_derivative_slice(X):
43 1 108 108.0 100.0 return (f(X[0:-2]) - 2*f(X[1:-1]) + f(X[2:]))/(h**2)
新方法更快。但是,我不明白为什么 21.5% 花费在这个初始化上 out[:, 0:3] = 1
【问题讨论】: