More Pythonic way to build random clusters in Python

James Briggs :

I would like to create a function which will create a uniform distribution random cluster centered around a set of co-ordinates and with a specified radius, I have done this with the below:

import numpy as np

# create cluster builder
def cluster(center, radius=10, n=50):
    xx = np.random.uniform(center[0]-radius, center[0]+radius, size=n)
    yy = np.random.uniform(center[1]-radius, center[1]+radius, size=n)
    zz = np.random.uniform(center[2]-radius, center[2]+radius, size=n)
    return xx, yy, zz

# create random cluster
xx1, yy1, zz1 = cluster((25, 15, 5))

This works as expected, but I just feel that they're must be a more Pythonic way to build the cluster function. Does anyone have any suggestions?

Divakar :

np.random.uniform also accepts low and high as arrays/lists. Hence, we can simply do -

c = np.asarray(center)
xx,yy,zz = np.random.uniform(c-radius, c+radius, size=(n,3)).T

If any older version only supported scalar low and high, we can use some scaling -

xx,yy,zz = np.random.uniform(size=(3,n))*radius*2 + c[:,None] - radius

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31723&siteId=1