Physicist
Physicist

Reputation: 3048

vectorized code for python

I have created an array storing the coordinates of N random points using npr.uniform(size=(N, 2)). Now I want to use a function that computes the Xtotal^2+Ytotal^2, where Xtotal and Ytotal are the sum of the N x-coordinates and N y-coordinates respectively. I have no problem doing that by using a for loop, but now I want to run the program independently many times (more than 1000 times), and the only way I can think of is to use a for loop. Is it possible to do it in vectorized code to make it run faster? The actual project I'm doing is a bit more complicated and it would be too hard to describe it here, but I guess if I can solve this simplified program I will have no problem doing the harder one.

thanks

Upvotes: 0

Views: 86

Answers (2)

elyase
elyase

Reputation: 40973

Is this what you want?

>>> N = 5
>>> coords = np.random.uniform(size=(N, 2))
>>> coords

[[ 0.00510663  0.52338403]
 [ 0.88250555  0.0440339 ]
 [ 0.1753249   0.4534223 ]
 [ 0.13600696  0.71194949]
 [ 0.87044574  0.80934245]]

>>> coords.sum(axis=0)
array([ 2.31797242,  0.95364616])

>>> (coords.sum(axis=0)**2).sum()
12.247833350611774

If you want to repeat this 1000 times, then you can try to generate 1000*5 random numbers. Note that if you are doing complex processing(instead of just sums and powers), then in general your 1000 repetitions can't be vectorized.

Upvotes: 1

ev-br
ev-br

Reputation: 26050

Assuming your npr is numpy.random,

>>> import numpy as np
>>> N = 5
>>> xy = np.random.uniform(size=(N, 2))
>>> xy[:, 0]
array([ 0.91602043,  0.14053012,  0.01789579,  0.84857576,  0.20245375])
>>> xy[:, 1]
array([ 0.39608331,  0.46119256,  0.23600489,  0.93313743,  0.9790776 ])

Then just use slicing and indexing:

>>> xy[:, 0]**2 + xy[:, 1]**2
array([ 0.99597542,  0.23244729,  0.05601857,  1.5908263 ,  0.99958046])
>>> 
>>> xy[0, :]**2 + xy[1, :]**2
array([ 0.85884215,  0.36958056])

Upvotes: 1

Related Questions