电场线

时间:2018-11-13 07:26:08

标签: python numpy

L = 10
Ex = np.zeros([L,L])         # 2D array to store the Ex and
Ey = np.zeros([L,L])  

nq = 2
for i in range(nq): 
    q = random.randrange(-1,2,1) #indicates charge is poistive or negative
    qx = random.randrange(1,N) #indicates the positions of the charge
    qy = random.randrange(1,N)
for i in range(N): 
    for j in range(N): 
        denom = (((i-qx)**2.0+(j-qy)**2.0)**(1.5))
        if denom != 0: 
            Ex[i,j] += (q*(i-qx))/ denom
            Ey[i,j] += (q*(j-qy))/denom
        else: 
            continue

plot(Ex, Ey, color='b') #Could this code also be optimized in streamplot?
show() 

在此程序中,我试图创建2个电荷的电场线(希望是N#个电荷)。我的方法如下:

第一步: 定义一个LxL的窗口

第2步: 随机选择电荷位置并确定幅度。(在这种情况下,我认为幅度为-1,0,1) -我的随机位置需要为二维吗?

Step3: 为E选择一个数组 Ex(L,L)和Ey(L,L)

Step4: 在ix和iy上的嵌套循环中

Ex = x / r ** 3,x =(dx-ix)a,其中a是间距。

当前,看来我的代码目前只绘制了1个电荷。

1 个答案:

答案 0 :(得分:1)

要获得所需的内容,可以使用quiver绘图,并应纠正代码中的错误。这是修改代码以可视化电场强度的方法:

import numpy as np
import matplotlib.pyplot as plt
import random

np.seterr(divide='ignore', invalid='ignore')

# grid size
N = 15
M = 25
# coordinates
X = np.arange(0, M, 1)
Y = np.arange(0, N, 1)
X, Y = np.meshgrid(X, Y)
# strength
Ex = np.zeros((N, M))
Ey = np.zeros((N, M))
# amount of charges
nq = 3

# computing
qq = [[], []]  # to store charges coordinates
for dummy in range(nq): 
    q = random.choice([-1, 1])
    qx, qy = random.randrange(1, N), random.randrange(1, M)
    # print(q, qx, qy)
    qq[0].append(qy)
    qq[1].append(qx)
    for i in range(N):
        for j in range(M):
            denom = ((i - qx) ** 2 + (j - qy) ** 2) ** 1.5
            if denom != 0: 
                Ex[i, j] += q * (j - qy) / denom
                Ey[i, j] += q * (i - qx) / denom

# arrows color
C = np.hypot(Ex, Ey)
# normalized values for arrows to be of equal length
E = (Ex ** 2 + Ey ** 2) ** .5
Ex = Ex / E
Ey = Ey / E

# drawing
plt.figure(figsize=(12, 8))
# charges
plt.plot(*qq, 'bo')
# field
plt.quiver(X, Y, Ex, Ey, C, pivot='mid')
# colorbar for magnitude
cbar = plt.colorbar()
cbar.ax.set_ylabel('Magnitude')
# misc
plt.title('Electric Field Strength')
plt.axis('equal')
plt.axis('off')
plt.show()

结果:

enter image description here