簡體   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