# How to generate a set of random points within a given (x,y) coordinates in an x-y plane?

350
June 05, 2017, at 03:30 AM

Suppose I want to take 4 clusters of points. Each cluster can be within a given set of x-y co ordinates. Each point within a cluster is a random generated point.

These clusters will be acting as input for my K-Means clustering problem. How do I do it using Python?

This might give you some ideas:

``````from random import random
import math
def rand_cluster(n,c,r):
"""returns n random points in disk of radius r centered at c"""
x,y = c
points = []
for i in range(n):
theta = 2*math.pi*random()
s = r*random()
points.append((x+s*math.cos(theta), y+s*math.sin(theta)))
return points
``````

This function can be used in various ways, for example:

``````def rand_clusters(k,n,r, a,b,c,d):
"""return k clusters of n points each in random disks of radius r
where the centers of the disk are chosen randomly in [a,b]x[c,d]"""
clusters = []
for _ in range(k):
x = a + (b-a)*random()
y = c + (d-c)*random()
clusters.extend(rand_cluster(n,(x,y),r))
return clusters
``````

A typical all would look like

``````clusters = rand_clusters(4,50,0.3,0,1,0,1)
``````

This generates 4 clusters of size 50 of radius `0.3` with centers chosen at random in the unit square. Points from a typical run:

If you generate data using

``````min + (max - min) * random()
``````

Then they will be between min and max.

Do this for x and y, and for every cluster.

POPULAR ONLINE

### Getting encoding error while writing data to csv file

I am trying to write tweets to to csv file with columns 'username', 'Tweet', 'Timezone', 'Location', and 'Timestamp'

352

### carriage return without line break on windows

So I have this simple statusbar implementation:

396

### paper money detection by image processing using python and opencv on raspberry pi3

A part of my graduation project is to make a system that can detect original paper money and fake moneyI have raspberry pi 3 and pi camera so I decide to use opencv with raspberry pi to image processing the money and compare it to a standard

354

### Longest sequence of consecutive letters

Suppose I have a string of lower case letters, eg

393