题目:给定一个RL电路(10Ω电阻和5H电感串联),电源电压为12V,分析电感电流在5s内的变化,并用多项式进行拟合,并画出曲线图。
一、题目中功能要求
1.电路图思考
2.多项式拟合
3.画出曲线图
二、代码实现
# 第一阶段:设置环境和安装包
import Pkg
# 创建并激活新的项目环境
env_path = mktempdir()
Pkg.activate(env_path)
println("创建临时环境:", env_path)
# 安装所需包
Pkg.add(name="DifferentialEquations", version="7.9.0")
Pkg.add(name="Polynomials", version="4.0.0")
Pkg.add(name="Plots", version="1.39.0")
Pkg.add(name="CSV", version="0.10.13")
Pkg.add(name="DataFrames", version="1.6.1")
Pkg.add(name="Printf")
println("安装完成!")
# 第二阶段:实际分析代码
begin
using DifferentialEquations
using Polynomials
using Plots
using CSV
using DataFrames
using Printf
# RL电路参数
R = 10.0 # 电阻 (Ω)
L = 5.0 # 电感 (H)
V = 12.0 # 电源电压 (V)
t_end = 5.0 # 分析时间 (s)
println("\n开始分析 RL 电路...")
@printf "电路参数: R = %.1f Ω, L = %.1f H, V = %.1f V\n" R L V
# 定义RL电路微分方程
function rl_circuit!(du, u, p, t)
du[1] = (V - R * u[1]) / L
end
# 初始条件
u0 = [0.0] # t=0时电流为0
tspan = (0.0, t_end)
# 求解微分方程
println("求解微分方程...")
prob = ODEProblem(rl_circuit!, u0, tspan)
sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, saveat=0.1)
# 提取时间和电流数据
t_data = sol.t
i_data = [u[1] for u in sol.u]
# 解析解(理论值)
τ = L / R # 时间常数
i_steady = V / R # 稳态电流
analytic(t) = i_steady * (1 - exp(-t/τ))
# 进行多项式拟合(5阶多项式)
println("进行多项式拟合...")
fit_poly = fit(t_data, i_data, 5)
# 计算拟合曲线
i_fit = fit_poly.(t_data)
# 计算拟合误差
err_fit = i_data - i_fit
mse = sum(err_fit.^2) / length(t_data)
max_err = maximum(abs.(err_fit))
# 输出结果
println("\n电路分析结果:")
@printf " 时间常数 τ = L/R = %.3f s\n" τ
@printf " 稳态电流 I_∞ = V/R = %.3f A\n" i_steady
@printf " 多项式拟合均方误差 (MSE) = %.6e A²\n" mse
@printf " 最大拟合误差 = %.6f A\n" max_err
@printf " 多项式: %s\n" fit_poly
# 创建数据框
df = DataFrame(
t = t_data,
current = i_data,
fit = i_fit,
analytic = analytic.(t_data),
fit_error = err_fit,
analytic_error = i_data - analytic.(t_data)
)
# 保存数据 - 使用安全路径
desktop_path = joinpath(homedir(), "Desktop", "rl_circuit_data.csv")
CSV.write(desktop_path, df)
println("\n数据已保存到: ", desktop_path)
# 创建绘图 - 使用GR后端(更可靠)
println("创建图表...")
Plots.gr() # 使用GR后端(默认,更可靠)
# 创建主图
plt = Plots.plot(
title = "RL电路电流分析 (R=$R Ω, L=$L H)",
xlabel = "时间 (s)",
ylabel = "电流 (A)",
legend = :bottomright,
size = (900, 500),
grid = true
)
# 添加曲线
Plots.plot!(plt, t_data, i_data,
label = "数值解",
linewidth = 2,
color = :blue)
Plots.plot!(plt, t_data, i_fit,
label = "多项式拟合 (5阶)",
linewidth = 2,
linestyle = :dash,
color = :red)
Plots.plot!(plt, t_data, analytic.(t_data),
label = "解析解",
linewidth = 2,
linestyle = :dot,
color = :green)
Plots.hline!(plt, [i_steady],
label = "稳态电流 ($(i_steady) A)",
linewidth = 1.5,
linestyle = :dashdot,
color = :black)
Plots.vline!(plt, [τ],
label = "时间常数 τ ($τ s)",
linewidth = 1.5,
linestyle = :dashdot,
color = :orange)
# 添加误差统计 - 明确使用 Plots.text
Plots.annotate!(plt, t_end*0.6, i_steady*0.8,
Plots.text("拟合多项式: $(fit_poly)", 7, :left, :red))
Plots.annotate!(plt, t_end*0.6, i_steady*0.6,
Plots.text(@sprintf("均方误差: %.2e A²", mse), 9))
Plots.annotate!(plt, t_end*0.6, i_steady*0.5,
Plots.text(@sprintf("最大误差: %.6f A", max_err), 9))
# 保存为PNG文件
img_path = joinpath(homedir(), "Desktop", "rl_circuit_analysis.png")
Plots.savefig(plt, img_path)
println("图表已保存到: ", img_path)
# 在控制台显示关键结果
println("\n关键时间点数据:")
println("时间(s)\t数值解(A)\t解析解(A)\t拟合值(A)")
println("─"^60)
for t in [0.0, τ/2, τ, τ*2, τ*4, t_end]
i_val = sol(t)[1]
i_an = analytic(t)
i_poly = fit_poly(t)
@printf("%5.2f\t%10.5f\t%10.5f\t%10.5f\n", t, i_val, i_an, i_poly)
end
# 显示多项式系数
coeffs = fit_poly.coeffs
println("\n多项式系数 (电流 = a + b*t + c*t^2 + d*t^3 + e*t^4 + f*t^5):")
@printf(" 常数项 (a): %.8f\n", coeffs[1])
for i in 2:length(coeffs)
@printf(" t^%d 系数: %.8f\n", i-1, coeffs[i])
end
println("\n分析完成! 所有结果已保存到文件:")
println(" - 电路数据: ", desktop_path)
println(" - 图表: ", img_path)
end
三、结果展示
四、疑问
1.波形标题没显示出来可能和输入的是中文有关,或者是出了点小问题,由于快到期末周了就暂不改进了;
2.若本代码报错,有以下几种可能:
(1)未安装包/包没更新;
(2)查看具体报错信息,咨询AI辅助修改。