[英]Numpy gradient for a 2 dimensions array
I'm not sure of how to use numpy.gradient().我不确定如何使用 numpy.gradient()。
to compute the partial derivatives (2nd order) I was using for loops :计算偏导数(二阶)我使用的循环:
for j in range(1, nx-1):
d2px[:, j] = (p[:, j - 1] - 2 * p[:, j] + p[:, j + 1]) / dx ** 2
for i in range(1, ny-1):
d2py[i, :] = (p[i - 1, :] - 2 * p[i, :] + p[i + 1, :]) / dy ** 2
And I tried to replace it with numpy.gradient : (for x here)我试图用 numpy.gradient 替换它:(这里是 x)
dpx = np.gradient(p, [1, dx], axis = 0)
d2px = np.gradient(dpx, [1, dx])
But I always have the same error message :但我总是有相同的错误信息:
"ValueError: when 1d, distances must match the length of the corresponding dimension"
“ValueError:当为1d时,距离必须与对应维度的长度相匹配”
with the following code :使用以下代码:
x = np.linspace(0, nx, nx) # coordonnées selon x...
dpx = np.gradient(p, x, axis = 0)
d2px_test = np.gradient(dpx, x, axis = 0)
the input p is :输入 p 是:
[[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00]
[ 0.00000000e+00 6.53832270e-23 -1.19328961e-22 6.53832270e-23
0.00000000e+00]
[ 0.00000000e+00 -1.19328961e-22 2.07190726e-22 -1.19328961e-22
0.00000000e+00]
[ 0.00000000e+00 6.53832270e-23 -1.19328961e-22 6.53832270e-23
0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00]]
The expected output is :预期的输出是:
[[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00]
[ 0.00000000e+00 -2.50095415e-20 3.69424377e-20 -2.50095415e-20
0.00000000e+00]
[ 0.00000000e+00 4.45848648e-20 -6.53039374e-20 4.45848648e-20
0.00000000e+00]
[ 0.00000000e+00 -2.50095415e-20 3.69424377e-20 -2.50095415e-20
0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00]]
And the actual output is :实际输出是:
[[ 0.00000000e+00 -8.00305329e-23 1.42671568e-22 -8.00305329e-23
0.00000000e+00]
[ 0.00000000e+00 -2.09226327e-23 3.81852676e-23 -2.09226327e-23
0.00000000e+00]
[ 0.00000000e+00 3.81852676e-23 -6.63010323e-23 3.81852676e-23
0.00000000e+00]
[ 0.00000000e+00 -2.09226327e-23 3.81852676e-23 -2.09226327e-23
0.00000000e+00]
[ 0.00000000e+00 -8.00305329e-23 1.42671568e-22 -8.00305329e-23
0.00000000e+00]]
In terms of visualisation : the expected output is :在可视化方面:预期输出是:
And the actual output (with np.gradient) is :实际输出(使用 np.gradient)是:
Thanks for your help.谢谢你的帮助。
You can simply vectorize the operation您可以简单地矢量化操作
d2px2 = (p[:, :-2] - 2 * p[:, 1:-1] + p[:, 2:]) / dx ** 2
d2py2 = (p[:-2, :] - 2 * p[1:-1, :] + p[2:, :]) / dy ** 2
np.allclose(d2px2, d2px[:, 1:])
# True
np.allclose(d2py2, d2py[1:, :])
# True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.