我试图模拟一个粒子在经历电斥力(或引力)时,与另一个粒子相撞,这被称为卢瑟福散射。我已经成功地使用for循环和python列表模拟了(一些)粒子。但是,现在我想改用numpy数组。模型将使用以下步骤:
我的问题是我不知道如何使用numpy数组来计算力分量。 下面是我不可运行的代码
import numpy as np
# I used this function to calculate the force while using for-loops.
def force(x1, y1, x2, x2):
angle = math.atan((y2 - y1)/(x2 - x1))
dr = ((x1-x2)**2 + (y1-y2)**2)**0.5
force = charge2 * charge2 / dr**2
xforce = math.cos(angle) * force
yforce = math.sin(angle) * force
# The direction of force depends on relative location
if x1 > x2 and y1<y2:
xforce = xforce
yforce = yforce
elif x1< x2 and y1< y2:
xforce = -1 * xforce
yforce = -1 * yforce
elif x1 > x2 and y1 > y2:
xforce = xforce
yforce = yforce
else:
xforce = -1 * xforce
yforce = -1* yforce
return xforce, yforce
def update(array):
# this for loop defeats the entire use of numpy arrays
for particle in range(len(array[0])):
# find distance of all particles pov from 1 particle
# find all x-forces and y-forces on that particle
xforce = # sum of all x-forces from all particles
yforce = # sum of all y-forces from all particles
force_arr[0, particle] = xforce
force_arr[1, particle] = yforce
return force
# begin parameters
t = 0
N = 3
masses = np.ones(N)
charges = np.ones(N)
loc_arr = np.random.rand(2, N)
speed_arr = np.random.rand(2, N)
acc_arr = np.random.rand(2, N)
force = np.random.rand(2, N)
while t < 0.5:
force_arr = update(loc_arry)
acc_arr = force_arr / masses
speed_arr += acc_array
loc_arr += speed_arr
t += dt
# plot animation
用阵列对此问题建模的一种方法可能是:
Nx2
数组。(如果以后升级到三维点,这将有助于扩展性)distance
、angle
、force
定义为NxN
数组以表示成对交互需要了解的重要事项:
meshgrid
帮助您生成调整Nx2
数组形状以计算NxN
结果所需的数组索引arctan2()
计算有符号角度,因此可以绕过复杂的“哪个象限”逻辑例如,你可以做这样的事情。注意
get_dist
和get_angle
中点之间的算术运算发生在最底部的维度中:对于上面显示的示例3点向量:
这里有一个围棋,每个时间步只有一个循环,它应该适用于任意数量的维度,我也用3个维度进行了测试:
上面的示例生成,其中黑色和蓝色点分别表示开始和结束位置:
当电荷相等时
charges = np.ones(N) * 2
系统对称性得以保持,电荷相互排斥:最后是一些随机初始速度
speed_arr = np.random.rand(N, 2)
:编辑
对上面的代码做了一个小改动,以确保它是正确的。(我在合力上遗漏了-1,即+/+之间的力应该是负数,我总结了错误的轴,对此表示歉意。现在在
masses[0] = 5
的情况下,系统正确发展:相关问题 更多 >
编程相关推荐