python - 电场线

标签 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的窗口

第二步: 随机选择电荷位置并确定其大小。(在本例中,我只是将其大小设为 -1,0,1) - 我的随机位置需要是二维的吗?

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

第四步: 在 ix 和 iy 的嵌套循环中

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

目前,我的代码似乎只绘制了 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

关于python - 电场线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53275867/

相关文章:

python - 检查实例是否存在于列表中

python - Flask jsonify 对象列表

python - 通过 numpy.copy 复制字典。现在是ndarray;如何恢复原来的字典?

python-3.x - 导入tensorflow时出现以下错误: No module named 'numpy.core._multiarray_umath'

python - 在django中使用注释引用相关对象

python - 使用 numpy ufuncs 就地修改 Pandas 数据框

python - 如何在ndarray中找到数字层的总和

python - Numpy 2D Array - Power Of - 不返回答案?

python - 按组连接字符串python

python - 从数据采集单元读取数据(测量计算)