标题可能含糊不清,不知道该怎么说。
我在 python 中使用 numpy 和 matplotlib 的粒子模拟器已经有点远了,我已经设法实现了 coloumb、重力和风,现在我只想添加温度和压力,但我有一个优化前的问题(万恶之源)。我想看看粒子何时崩溃:
问:在 numpy 中是否可以根据 bool 条件来获取数组与每个元素的差异?我想避免循环。
例如:(x - any element in x) < a
应该返回类似
[True, True, False, True]
如果 x 中的元素 0,1 和 3 满足条件。
编辑:
等效循环是:
for i in len(x):
for j in in len(x):
#!= not so important
##earlier question I asked lets me figure that one out
if i!=j:
if x[j] - x[i] < a:
True
我注意到 numpy 操作比 if 测试快得多,这帮助我加快了速度。
如果有人想玩它,这是一个示例代码。
#Simple circular box simulator, part of part_sim
#Restructure to import into gravity() or coloumb () or wind() or pressure()
#Or to use all forces: sim_full()
#Note: Implement crashing as backbone to all forces
import numpy as np
import matplotlib.pyplot as plt
N = 1000 #Number of particles
R = 8000 #Radius of box
r = np.random.randint(0,R/2,2*N).reshape(N,2)
v = np.random.randint(-200,200,r.shape)
v_limit = 10000 #Speedlimit
plt.ion()
line, = plt.plot([],'o')
plt.axis([-10000,10000,-10000,10000])
while True:
r_hit = np.sqrt(np.sum(r**2,axis=1))>R #Who let the dogs out, who, who?
r_nhit = ~r_hit
N_rhit = r_hit[r_hit].shape[0]
r[r_hit] = r[r_hit] - 0.1*v[r_hit] #Get the dogs back inside
r[r_nhit] = r[r_nhit] +0.1*v[r_nhit]
#Dogs should turn tail before they crash!
#---
#---crash code here....
#---crash end
#---
vmin, vmax = np.min(v), np.max(v)
#Give the particles a random kick when they hit the wall
v[r_hit] = -v[r_hit] + np.random.randint(vmin, vmax, (N_rhit,2))
#Slow down honey
v_abs = np.abs(v) > v_limit
#Hit the wall at too high v honey? You are getting a speed reduction
v[v_abs] *=0.5
line.set_ydata(r[:,1])
line.set_xdata(r[:,0])
plt.draw()
一旦我弄清楚如何......以便可以在更大的盒子中轻松区分高速粒子,我计划为上面的数据点添加颜色。