详见python小程序
import numpy as np import matplotlib.pyplot as plt # 定义常量 k = 8.99e9 # 库仑常数 (N m^2/C^2) # 定义电荷类 class PointCharge: def __init__(self, charge, position): self.charge = charge self.position = np.array(position) def electric_field(self, X, Y): # 计算电场 r_vector = np.dstack((X, Y)) - self.position r_magnitude = np.linalg.norm(r_vector, axis=2) # 防止除以零 r_magnitude[r_magnitude == 0] = np.inf E_magnitude = k * self.charge / r_magnitude**2 E_direction = r_vector / r_magnitude[:, :, np.newaxis] # 单位矢量 return E_magnitude[:, :, np.newaxis] * E_direction @staticmethod def calculate_electric_field(charges,X, Y): # 初始化电场 E_field = np.zeros((X.shape[0], X.shape[1], 2)) # 计算每个电荷的电场并叠加 for charge in charges: E_field += charge.electric_field(X, Y) # 计算电场的分量 Ex = E_field[:, :, 0] Ey = E_field[:, :, 1] return Ex, Ey @staticmethod def plot_electric_field(X,Y,Ex,Ey): # 绘制电场线 plt.figure(figsize=(10, 10)) # 使用 streamplot 绘制电场线 plt.streamplot(X, Y, Ex, Ey, color='b', linewidth=1.5, density=1.5) # 绘制电荷位置 for charge in charges: plt.plot(charge.position[0], charge.position[1], 'ro' if charge.charge > 0 else 'bo', markersize=10) plt.xlim(-5, 5) plt.ylim(-5, 5) plt.title('Electric Field of Multiple Point Charges') plt.xlabel('x (m)') plt.ylabel('y (m)') plt.grid() plt.axis('equal') plt.show() if __name__ == '__main__': # 创建多个电荷 charges = [ PointCharge(1e-6, (-2, -2)), # 正电荷 # PointCharge(-1e-6, (2, 0)), # 负电荷 PointCharge(1e-6, (2, 2)), # 正电荷 # PointCharge(-1e-6, (0, -2)), # 负电荷 ] # 定义网格 x = np.linspace(-5, 5, 20) y = np.linspace(-5, 5, 20) X, Y = np.meshgrid(x, y) Ex,Ey= PointCharge.calculate_electric_field(charges, X, Y) # 绘制电场线 PointCharge.plot_electric_field(X, Y, Ex, Ey)
标签:plt,电场,PointCharge,field,charge,magnitude,np,绘制 From: https://www.cnblogs.com/dogingate/p/18549450