在下面的代码中,我找到了微分方程组的解。我已经在这段代码中绘制了相空间轨迹,它工作正常。然而,我想重复情节,但用箭头来帮助我清楚地展示情节的含义。
我看到有人问过类似的问题:
Drawing phase space trajectories with arrows in matplotlib
因此在下面的代码中,我试图根据我的情况复制它。 (我会在那个帖子上发布这个问题,但它不允许我这样做)
当我运行代码时,我得到的图像如下:
显然我在某些时候误解了 quiver 函数(因为图应该看起来一样(只有第二个应该有箭头)这显然不是这种情况,我也看到改变我的 linspace 中的点数会改变第二个情节严重)。
我的代码如下:
# Import the required modules
import numpy as np
from run_kut4 import *
from printSoln import *
import pylab
def G2(x,y):
G2=np.zeros(2)
G2[0]=y[1]
G2[1]=-np.sin(y[0])+0.02*np.cos(y[0])*np.sin(x)
return G2
x2=0.0
xstop2=40.0
y2=np.array([0.0,0.0])
h2=0.005#step size
#freq=1
X2,Y2=integrate(G2,x2,y2,xstop2,h2)
pylab.plot(Y2[:,0],Y2[:,1])
pylab.xlabel('θ')
pylab.ylabel('dθ/dx')
pylab.title('Phase space trajectory (resonant case)')
pylab.show()
y1=np.linspace(-0.4,0.4,100)
y2=np.linspace(-0.4,0.4,100)
U,V=np.meshgrid(y1,y2)
pylab.quiver(U,V,Y2[:,0],Y2[:,1])
pylab.xlabel('θ')
pylab.ylabel('dθ/dx')
pylab.title('Phase space trajectory (resonant case)')
pylab.show()
我只是想知道是否有人能看到我哪里出错了,任何帮助表示赞赏。谢谢 :)
我试图按照语法建议切换 U 和 V,并得到了这个:
使用的 Runge Kutta 代码:
## module run_kut4
''' X,Y = integrate(F,x,y,xStop,h).
4th-order Runge-Kutta method for solving the
initial value problem {y}' = {F(x,{y})}, where
{y} = {y[0],y[1],...y[n-1]}.
x,y = initial conditions
xStop = terminal value of x
h = increment of x used in integration
F = user-supplied function that returns the
array F(x,y) = {y'[0],y'[1],...,y'[n-1]}.
'''
import numpy as np
def integrate(F,x,y,xStop,h):
def run_kut4(F,x,y,h):
K0 = h*F(x,y)
K1 = h*F(x + h/2.0, y + K0/2.0)
K2 = h*F(x + h/2.0, y + K1/2.0)
K3 = h*F(x + h, y + K2)
return (K0 + 2.0*K1 + 2.0*K2 + K3)/6.0
X = []
Y = []
X.append(x)
Y.append(y)
while x < xStop:
h = min(h,xStop - x)
y = y + run_kut4(F,x,y,h)
x = x + h
X.append(x)
Y.append(y)
return np.array(X),np.array(Y)
最佳答案
"Drawing phase space trajectories in Matplotlib with arrows"中给出的代码如果您减小步长 h=0.1
也适用于您的情况.我们可以生成下图。
# Import the required modules
import numpy as np
from run_kut4 import *
import pylab
def G2(x,y):
G2=np.zeros(2)
G2[0]=y[1]
G2[1]=-np.sin(y[0])+0.02*np.cos(y[0])*np.sin(x)
return G2
x2=0.0
xstop2=40.0
y2=np.array([0.0,0.0])
h2=0.1#step size
#freq=1
X2,Y2=integrate(G2,x2,y2,xstop2,h2)
#pylab.plot(Y2[:,0],Y2[:,1])
pylab.xlabel('θ')
pylab.ylabel('dθ/dx')
pylab.title('Phase space trajectory (resonant case)')
pylab.show()
pylab.quiver(Y2[:-1,0], Y2[:-1,1], Y2[1:,0]-Y2[:-1,0], Y2[1:,1]-Y2[:-1, 1])
pylab.xlabel('θ')
pylab.ylabel('dθ/dx')
pylab.title('Phase space trajectory (resonant case)')
pylab.show()
如果你不喜欢前面的情节,你可以跳过
quiver
完全绘图,只需将绘图命令更改为 pylab.plot(Y2[:,0],Y2[:,1],'->')
.这给出了一个像关于Python-绘制相空间轨迹(颤动函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47740558/