赞
踩
看到这个标题肯定有人会问:好好的multisim、 proteus之类的专门电路仿真软件不用,非要写一个简陋的python程序来弄,是不是精神失常了。实际上,我也不知道为什么要这么干,前两篇文章是我实际项目中的一些探索,但是这个纯属突发奇想。
pip install matplotlib
我设计了一个计算了"串联分压"电路中的总电流以及每个电阻上的电压降的程序,如下。
- import matplotlib.pyplot as plt
- import matplotlib.patches as patches
-
- plt.rcParams['font.sans-serif'] = ['SimHei']
- plt.rcParams['axes.unicode_minus'] = False
-
- def simulate_series_circuit(V, resistances):
- """模拟一个给定电压(V)和一系列电阻值的串联电路。"""
- # 计算总电阻
- R_total = sum(resistances)
- # 根据欧姆定律计算电流: V = I * R
- I = V / R_total if R_total > 0 else 0
- # 计算每个电阻上的电压降
- voltage_drops = [I * R for R in resistances]
-
- return I, voltage_drops
-
-
- def draw_circuit(resistances, voltage_drops, current):
- """绘制电路图并显示电压降和电流。"""
- fig, ax = plt.subplots()
-
- # 创建电池图例
- battery = patches.Rectangle((1, -0.25), 0.2, 0.5, edgecolor='black', facecolor='grey', label='电源')
- ax.add_patch(battery)
- plt.text(1.1, 0, '电源', horizontalalignment='center', verticalalignment='center')
-
- # 绘制电阻并显示电压
- for i, (R, V) in enumerate(zip(resistances, voltage_drops)):
- resistor_x = 2 + i * 1.5
- resistor = patches.Rectangle((resistor_x, -0.25), 1, 0.5, edgecolor='black', facecolor='orange',
- label=f'电阻 R{i + 1}' if i == 0 else "")
- ax.add_patch(resistor)
- plt.text(resistor_x + 0.5, 0, f'{V:.2f}V', horizontalalignment='center', verticalalignment='center')
-
- # 绘制导线
- plt.plot([1.2, 2], [0, 0], color='black', label='导线')
- for i in range(len(resistances) - 1):
- plt.plot([3 + i * 1.5, 3.5 + i * 1.5], [0, 0], color='black')
- plt.plot([2 + len(resistances) * 1.5, 3 + len(resistances) * 1.5], [0, 0], color='black')
-
- # 绘制从电路末端返回电池的线路
- plt.plot([3 + len(resistances) * 1.5, 3 + len(resistances) * 1.5, 1], [0, -0.25, -0.25], color='black')
-
- # 添加电流标签
- plt.text(1.5 + len(resistances) * 1.5, 0.3, f'电流 = {current:.2f}A', horizontalalignment='center',
- verticalalignment='center')
-
- # 设置限制并关闭坐标轴
- 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, loc='upper 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Ω)
观察运行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。