Performing external upload with numpy

Sorry if this is a stupid question, but I'm just starting out with python / numpy, and I'm really not sure about the most efficient solutions. I am building an N-body demo for some students, but for now I am calculating the force between the particles, looping the positions of these particles, which are predictably slower than molasses. Basically, given the vector x[i] , I would like to calculate:

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

using numpy functions, not a loop. If there is a way to do external addition / multiplication:

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

I could use this to calculate.

+5
source share
2 answers

All generic functions that take two input arguments have an outer attribute:

 x = np.array([1, 2, 3]) np.subtract.outer(x, x) 

gives:

 array([[ 0, -1, -2], [ 1, 0, -1], [ 2, 1, 0]]) 

and

 np.multiply.outer(x, x) 

leads to:

 array([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) 
+11
source

Many of the main numpy operators, such as np.add , np.subtract , np.multiply , etc., are called universal functions (ufuncs) , and have (among other things) the .outer method:

 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]]) 

Another very powerful technique for this kind of thing is broadcasting :

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

Indexing with None (or alternatively with np.newaxis ) inserts a new dimension, so a[:, None] has the form (3, 1) and b[None, :] a[:, None] b[None, :] has the form (1, 5) . Broadcast “expands” the result by the size of a singleton, so that it has the form (3, 5) .

+7
source

Source: https://habr.com/ru/post/1236514/


All Articles