电场的绘制

详见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)
复制代码

 

posted on   风中狂笑  阅读(18)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示