繁体   English   中英

R和Python上的渐变函数

[英]Gradient function on R and Python

我在R中测试代码,然后我想在Python中使用类似的代码。 我有这个潜力: Z = 1/sqrt(Y^2+X^2+2*d*X+d^2) 我尝试使用pracma包用R绘制它,如下所示:

require(pracma)

range = seq(-15,15,by=1)
mesh = meshgrid(range,range)

X = mesh$X
Y = mesh$Y    
d = 5

# Now I define the potential:
Z = 1/sqrt(Y^2+X^2+2*d*X+d^2)
contour(range,range,t(Z),col="black",xlab="x",ylab="y")

# Now the gradient:
grX = gradient(Z,range,range)$X
grY = gradient(Z,range,range)$Y

# I wanted the vectors to be normalized so I did this:
grXN = grX/sqrt(grX^2+grY^2)
grYN = grY/sqrt(grX^2+grY^2)

# Finally I draw the vector field:
quiver(X,Y,grXN,grYN,scale=0.5,col="black")

当我运行这段代码时,我得到了这样的结果: R中的Quiver这或多或少是我想要的,除了它有点难看。

然后我在Python中使用这样的代码:

import numpy as np
import matplotlib.pyplot as plt

rng = np.arange(-15,15,1)
X,Y = np.meshgrid(rng,rng)
d = 5

# Now I define the potential:
Z = 1/np.sqrt(Y**2+X**2+2*d*X+d**2)

# Now the gradient:
grX,grY = np.gradient(Z)

# Since I want the vectors normalized I did this:
grXN = grX/np.sqrt(grX**2+grY**2)
grYN = grY/np.sqrt(grX**2+grY**2)

# In this case I made a different contour:
contor = plt.contourf(X,Y,Z,50)
cbar = plt.colorbar(contor)

# Finally the arrows:
Q = plt.quiver(X,Y,grXN,grYN,color="w",scale=30)

当我运行这段代码时,我得到了这个: Python中的箭头这很可爱,但与从R.获得的结果完全不同。为什么?

你的Python箭头相对于你的R箭头扭曲了90°。 原因是当涉及尺寸“X”和“Y”的顺序时, numpymatplotlib之间的约定差异。 出于(有争议的)直觉性的原因, matplotlib函数 - 就像它的疯狂叔叔Matlab那样 - 通常按顺序询问X,然后是Y. 同样,利用其灵感来自于Matlab的陈腐meshgrid功能, numpy.meshgrid也采用了该公约,在其indexing参数默认为'xy' 但我相信numpy.gradient必须遵循更常见的numpy -esque假设'ij'索引(并且在可视化数组时,Y通常是行到行'i'维度,在numpy数组中是维度0,所以然后X通常是列到列'j'维度,维度1)。 因此,你应该说:

grY,grX = np.gradient(Z)

代替

grX,grY = np.gradient(Z)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM