我正在測試R中的代碼,然後我想在Python中使用類似的代碼。我有這個潛力:Z = 1/sqrt(Y^2+X^2+2*d*X+d^2)
。我嘗試使用pracma包裝這樣有R繪製它:R和Python上的漸變函數
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")
當我運行這段代碼我得到這個: Quiver in R 這或多或少是我想要的東西,但它是一個有點難看。
然後我做了這個代碼在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)
當我運行這段代碼我得到這個: Quiver in Python 這是可愛的,但是從R.爲什麼得到的結果完全不同?
你用什麼版本的Python? – vaultah
我在使用2.7.13版本 –