Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active September 7, 2015 06:38
Show Gist options
  • Select an option

  • Save nikoheikkila/0ed87008532581b26e17 to your computer and use it in GitHub Desktop.

Select an option

Save nikoheikkila/0ed87008532581b26e17 to your computer and use it in GitHub Desktop.
Python function generates a random point inside a circle and returns its X and Y coordinates as a tuple.
import math
from random import random
def getRandomPointInCircle(radius):
"""
Function generates a random point inside a circle
and returns its X and Y coordinates as a tuple.
"""
t = 2 * math.pi * random()
u = random() + random()
r = None
if u > 1:
r = 2 - u
else:
r = u
result = radius * r * math.cos(t), radius * r * math.sin(t)
return result
# Main function for testing
if __name__ == "__main__":
point = None
for r in range(1, 100):
point = getRandomPointInCircle(r)
print "X: %d, Y: %d" % (point[0], point[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment