Prashant Mishra
Prashant Mishra

Reputation: 73

Generating random points on the circumference of a circle (python)

I was wondering how can i efficiently get the coordinate of random points on a circular locus. I tried the equation of the circle where (h,k) is the center, r is the radius and (x,k) is the randomly generated point.

(x−h)^2 + (y−k)^2 = r^2

I tried checking each randomly generated point whether it satisfies the equation, but this method is highly inefficient. Is there any way I can implement it in python?

Upvotes: 2

Views: 4798

Answers (1)

Robᵩ
Robᵩ

Reputation: 168626

Use trigonometry?

from math import pi, cos, sin
from random import random

def point(h, k, r):
    theta = random() * 2 * pi
    return h + cos(theta) * r, k + sin(theta) * r

Here is its use in a complete program:

import matplotlib.pyplot as plt
from math import pi, cos, sin
from random import random

def point(h, k, r):
    theta = random() * 2 * pi
    return h + cos(theta) * r, k + sin(theta) * r

xy = [point(1,2,1) for _ in range(30)]

plt.scatter(*zip(*xy))
plt.grid(color='k', linestyle=':', linewidth=1)
plt.axes().set_aspect('equal', 'datalim')
plt.show()

And the result:

enter image description here

Upvotes: 7

Related Questions