用numpy执行外部添加

Gra*_*eid 13 python numpy

很抱歉,如果这是一个愚蠢的问题,但我刚刚开始使用python/numpy,我真的不确定最有效的方法.我正在为一些学生组装一个演示N体模拟器,但是现在,我通过循环这些粒子的位置来计算粒子之间的力,这可以预测和糖蜜一样慢.基本上,给定一个向量x[i],我想计算:

n[i] = sum from j = 0 to n-1, j != i of (x[i]-x[j])^-2,
Run Code Online (Sandbox Code Playgroud)

使用numpy函数而不是循环.如果有办法执行外部加法/乘法:

m[i,j] = x[i]-x[j],

m[i,j] = x[i]*x[j],
Run Code Online (Sandbox Code Playgroud)

我可以用它来做计算.

Mik*_*ler 23

所有带有两个输入参数的通用函数都有一个属性outer:

x = np.array([1, 2, 3])
np.subtract.outer(x, x)
Run Code Online (Sandbox Code Playgroud)

得到:

array([[ 0, -1, -2],
       [ 1,  0, -1],
       [ 2,  1,  0]])
Run Code Online (Sandbox Code Playgroud)

np.multiply.outer(x, x)
Run Code Online (Sandbox Code Playgroud)

结果是:

array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很棒的功能!对于那些感兴趣的人,请进一步阅读[ufunc文档](https://docs.scipy.org/doc/numpy-1.13.0/reference/ufuncs.html#methods)。 (2认同)

ali*_*i_m 12

许多numpy的基本运营商如np.add,np.subtract,np.multiply等被称为通用功能(ufuncs) ,并有(其中包括)的.outer方法:

import numpy as np
a = np.arange(3)
b = np.arange(5)
c = np.add.outer(a, b)
print(repr(c))
# array([[0, 1, 2, 3, 4],
#        [1, 2, 3, 4, 5],
#        [2, 3, 4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

另一种非常强大的技术是广播:

print(repr(a[:, None] + b[None, :]))
# array([[0, 1, 2, 3, 4],
#        [1, 2, 3, 4, 5],
#        [2, 3, 4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

使用None(或替代地np.newaxis)插入索引新尺寸,因此a[:, None]具有形状(3, 1)b[None, :]具有形状(1, 5).广播沿着单身尺寸"扩展"结果,使其具有形状(3, 5).