使用欧拉方法求解常微分方程(ODE)的Python代码无法正常求解,请求技术协助
Let's break down the problems in your code and fix them step by step:
1. Incorrect Plotting Argument Order
Your solver function returns a tuple (ys, ts) where ys is the list of y-values and ts is the list of time points. When you pass this directly to plt.plot(), matplotlib interprets ys as the x-axis data and ts as the y-axis data — which is backwards! You need to unpack the tuple and pass the time values first (as x-axis), then the y-values (as y-axis).
2. Mismatched Time Ranges for Comparison
Your numerical solver runs up to tstop=50, but your analytical solution only generates data up to t=5. This means you can't see the full comparison of the Euler method's behavior over the entire time span.
3. Minor: Loop Termination Edge Case (Optional)
While not breaking your code, using while (t < tstop) might lead to an extra step that slightly exceeds tstop. You can adjust it to while t + dt <= tstop if you want to strictly stay within the target time, but this is more of a refinement than a critical bug.
Corrected Code
from math import * import numpy as np import matplotlib.pyplot as plt def funkce(y, t): return(-y) def euler_1(dt, y, t, funkce ): y = y + dt * funkce(y, t) t = t + dt return (y,t) def solver(y0, t0, tstop, dt, typ): y = y0 t = t0 ys = [y] ts = [t] while (t < tstop): (y,t) = typ(dt, y, t, funkce) ts.append(t) ys.append(y) return(ys,ts) # Fix 1: Unpack the solver's return values and pass in correct order (ts first, then ys) ys, ts = solver(1, 0, 50, 0.05, euler_1) plt.plot(ts, ys, label='Euler Method') # Fix 2: Match the analytical solution's time range to the solver's tstop=50 t_analytical = np.linspace(0, 50, 1000) # More points for smooth curve y_analytical = np.exp(-t_analytical) plt.plot(t_analytical, y_analytical, label='Analytical Solution') # Add labels and legend for clarity plt.xlabel('Time (t)') plt.ylabel('y(t)') plt.legend() plt.show()
Explanation of Changes
- We now unpack
ysandtsfrom the solver, then plotts(time) on the x-axis andys(solution values) on the y-axis — this aligns with how matplotlib expects plot data. - The analytical solution now uses
t_analyticalfrom 0 to 50, matching the solver's time span, so you can see how the Euler method compares over the entire range. - Added labels and a legend to make the plot easier to interpret.
When you run this corrected code, you'll see the Euler method's solution closely tracking the analytical exponential decay (especially with your small dt=0.05), which is exactly what you'd expect for this ODE.
内容的提问来源于stack exchange,提问作者Nitaa a

