我试图模拟一个粒子在经历电排斥(或吸引力)的同时向另一个粒子飞行,称为卢瑟福散射。我已经成功地使用 for 循环和 python 列表模拟了(一些)粒子。但是,现在我想改用 numpy 数组。该模型将使用以下步骤:
对于所有粒子:
计算所有其他粒子的径向距离
计算与所有其他粒子的角度
计算 x 方向和 y 方向的净力
使用 netto xForce 和 yForce 为每个粒子创建矩阵
通过 a = F/mass 创建加速度(也是 x 和 y 分量)矩阵
更新速度矩阵
更新位置矩阵
我的问题是我不知道如何使用 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
汪汪一只猫
月关宝盒
人到中年有点甜
相关分类