商务网站的主要内容,5118站长平台,网站建设专业网站设计公司物格网,厦门网站建设网站看到这个标题肯定有人会问#xff1a;好好的multisim、 proteus之类的专门电路仿真软件不用#xff0c;非要写一个简陋的python程序来弄#xff0c;是不是精神失常了。实际上#xff0c;我也不知道为什么要这么干#xff0c;前两篇文章是我实际项目中的一些探索#xff0… 看到这个标题肯定有人会问好好的multisim、 proteus之类的专门电路仿真软件不用非要写一个简陋的python程序来弄是不是精神失常了。实际上我也不知道为什么要这么干前两篇文章是我实际项目中的一些探索但是这个纯属突发奇想。 第一步装matplotlib库
pip install matplotlib 第二步复制并运行代码 我设计了一个计算了串联分压电路中的总电流以及每个电阻上的电压降的程序如下。
import matplotlib.pyplot as plt
import matplotlib.patches as patchesplt.rcParams[font.sans-serif] [SimHei]
plt.rcParams[axes.unicode_minus] Falsedef simulate_series_circuit(V, resistances):模拟一个给定电压(V)和一系列电阻值的串联电路。# 计算总电阻R_total sum(resistances)# 根据欧姆定律计算电流: V I * RI V / R_total if R_total 0 else 0# 计算每个电阻上的电压降voltage_drops [I * R for R in resistances]return I, voltage_dropsdef draw_circuit(resistances, voltage_drops, current):绘制电路图并显示电压降和电流。fig, ax plt.subplots()# 创建电池图例battery patches.Rectangle((1, -0.25), 0.2, 0.5, edgecolorblack, facecolorgrey, label电源)ax.add_patch(battery)plt.text(1.1, 0, 电源, horizontalalignmentcenter, verticalalignmentcenter)# 绘制电阻并显示电压for i, (R, V) in enumerate(zip(resistances, voltage_drops)):resistor_x 2 i * 1.5resistor patches.Rectangle((resistor_x, -0.25), 1, 0.5, edgecolorblack, facecolororange,labelf电阻 R{i 1} if i 0 else )ax.add_patch(resistor)plt.text(resistor_x 0.5, 0, f{V:.2f}V, horizontalalignmentcenter, verticalalignmentcenter)# 绘制导线plt.plot([1.2, 2], [0, 0], colorblack, label导线)for i in range(len(resistances) - 1):plt.plot([3 i * 1.5, 3.5 i * 1.5], [0, 0], colorblack)plt.plot([2 len(resistances) * 1.5, 3 len(resistances) * 1.5], [0, 0], colorblack)# 绘制从电路末端返回电池的线路plt.plot([3 len(resistances) * 1.5, 3 len(resistances) * 1.5, 1], [0, -0.25, -0.25], colorblack)# 添加电流标签plt.text(1.5 len(resistances) * 1.5, 0.3, f电流 {current:.2f}A, horizontalalignmentcenter,verticalalignmentcenter)# 设置限制并关闭坐标轴ax.set_xlim(0, 4 len(resistances) * 1.5)ax.set_ylim(-1, 1)plt.axis(off)# 显示图例handles, labels ax.get_legend_handles_labels()plt.legend(handles, labels, locupper right)plt.show()# 输入参数
V float(input(请输入电源电压 (伏特): ))
resistances [float(x) for x in input(请输入电路中的电阻值 (欧姆)用空格分隔: ).split()]# 运行仿真
current, voltage_drops simulate_series_circuit(V, resistances)# 绘制并显示电路
draw_circuit(resistances, voltage_drops, current)第三步输入总电压和每个电阻并观察运行结果 在运行窗口输入总电压例:220V,每个电阻(56Ω78Ω90Ω100Ω) 观察运行结果如下: