我有一個小的引數圖,我試圖將它從 Mathematica 轉換為 python。問題是我的 python 腳本與此不匹配,我正在努力使串列圖能夠像在 Mathematica 中使用的那樣作業。
你會如何使用 matplotlib 在 python 中撰寫這個?
With[{r = 2.1, dt = 0.5, tfinal = 7.0},
x = 1;
y = 0;
xylist = {{x, y}};
Do[
x = x - r y dt;
y = y r x dt;
AppendTo[xylist, {x, y}];
, {i, 0, tfinal, dt}];
p1 = ParametricPlot[{Cos[t], Sin[t]}, {t, 0, 2 \[Pi]},
PlotStyle -> Dashed];
p2 = ListPlot[xylist, Joined -> True, AspectRatio -> 1];
Show[p1, p2, PlotRange -> All]
]

# ========================= Python ========================= #
# Parameters
r = 2.1
tfinal = 7.0
dt = 0.5
n = int(tfinal/dt)
# Containers
tspan = np.linspace(0, tfinal, n)
xtraj = np.zeros(n 1)
ytraj = np.zeros(n 1)
x0 = 1 # Initialize X
y0 = 0 # Initialize Y
value = odeint(f1, [x0,y0],tspan) # ODE values
# Euler scheme to calculate trajectory
# Initialize
xtraj[0] = x0
ytraj[0] = y0
for i in range(n):
xtraj[i 1] = xtraj[i] - r*ytraj[i]*dt
ytraj[i 1] = ytraj[i] r*xtraj[i]*dt
fig, ax1 = plt.subplots(figsize=(9, 9))
# Plot ODE result portion
plt.plot(xtraj ,ytraj ,label='simulation $\Delta t = 0.1$, $r=1$, $T = 7$ ', color='#96CDCD', marker='o', linestyle='dashed', alpha=0.7)
theta = np.linspace( 0 , 2 * np.pi , 150 )
radius = 1
a = radius * np.cos( theta ) 0
b = radius * np.sin( theta ) 0
ax1.plot( a, b , label='actual, r=1', c='k')
ax1.set_aspect( 1 )
ax1.set(xlim=(-1.5, 1.5), ylim=(-1.5, 1.5), );
uj5u.com熱心網友回復:
問題在于,在您的 Mathematica 中,x每次迭代都會通過“do”回圈更新的值。代替
ytraj[i 1] = ytraj[i] r*xtraj[i]*dt
和
ytraj[i 1] = ytraj[i] r*xtraj[i 1]*dt
并且您將看到相同的結果(當然,取決于繪圖格式,例如顏色和線條樣式):

請注意,就目前而言,您的 Python 是一個正確實作的 Euler 積分器;這是你的 Mathematica 不太“歐拉”(它接近歐拉-克羅默方法,雖然不完全)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371228.html
