I used matplotlib.pyplot.contour
to draw a line, but the result is strange.
My python code:
import numpy as np
from matplotlib import pyplot as plt
N = 1000
E = np.linspace(-5,0,N)
V = np.linspace(0, 70,N)
E, V = np.meshgrid(E, V)
L = np.sqrt(-E)
R = -np.sqrt(E+V)/np.tan(np.sqrt(E+V))
plt.contour(V, E,(L-R),levels=[0])
plt.show()
The result is:
But when I use Mathematica, the result is different.
Mathematica code is:
ContourPlot[Sqrt[-en] == -Sqrt[en + V]/Tan[Sqrt[en + V]], {V, 0, 70}, {en, -5, 0}]
The result is:
The result that I want is Mathematica's result.
Why does matplotlib.pyplot.contour
give the wrong result? I am very confused!
It would be very appreciate if you can give me some idea! Thank you very much!
答案 0 :(得分:1)
matplotlib.pyplot.contour
给出的结果在数值上是正确的,但在数学上是错误的。
如果仅绘制tan(x)
,请检查会发生什么情况:
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0,2*np.pi,1000)
y = np.tan(x)
plt.plot(x,y)
plt.show()
您将在两极得到一条线。这是因为后续点已连接。
您可以使用np.inf
来处理大于特定数量的点,从而规避这一问题。例如。添加
y[np.abs(y)> 200] = np.inf
将导致
相同的方法可用于轮廓。
import numpy as np
from matplotlib import pyplot as plt
N = 1000
x = np.linspace(0, 70,N)
y = np.linspace(-5,0,N)
X,Y = np.meshgrid(x, y)
F = np.sqrt(-Y) + np.sqrt(Y+X)/np.tan(np.sqrt(Y+X))
F[np.abs(F) > 200] = np.inf
plt.contour(X, Y, F, levels=[0])
plt.show()