用numpy执行外部加法 [英] performing outer addition with numpy
问题描述
很抱歉,如果这是一个愚蠢的问题,但是我刚开始使用python/numpy,我真的不确定最有效的处理方法.我正在为一些学生准备一个演示N体模拟器,但是现在,我正在通过循环这些粒子的位置来计算粒子之间的力,这可以想象与糖蜜一样慢.基本上,给定向量x[i]
,我想计算:
Sorry if this is a silly question but I am just getting started with python/numpy and I'm really not sure of the most efficient ways to go about things. I'm putting together a demo N-body simulator for some students, but for now, I am computing the force between particles by looping over the positions of those particles which is predictably as slow as molasses. Basically, given a vector x[i]
, I would like to compute:
n[i] = sum from j = 0 to n-1, j != i of (x[i]-x[j])^-2,
使用numpy函数而不是循环.如果可以执行外部加法/乘法:
using numpy functions rather than looping. If there is a way to perform outer addition/multiplication:
m[i,j] = x[i]-x[j],
m[i,j] = x[i]*x[j],
我可以用它来进行计算.
I could use that to do the computation.
推荐答案
所有带有两个输入参数的通用函数都具有属性outer
:
All universal functions that take two input arguments have an attribute outer
:
x = np.array([1, 2, 3])
np.subtract.outer(x, x)
给予:
array([[ 0, -1, -2],
[ 1, 0, -1],
[ 2, 1, 0]])
和
np.multiply.outer(x, x)
导致:
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
这篇关于用numpy执行外部加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!