Created
January 7, 2012 19:32
-
-
Save blacktaxi/1575749 to your computer and use it in GitHub Desktop.
Generating random points inside a circle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
random.seed() | |
import math | |
def rnd(_from=0, _to=1): return _from + random.random() * (_to - _from) | |
def rectangle_random(W=2, H=2): | |
return (rnd(0, W), rnd(0, H)) | |
def triangle_random(W=2, H=2): | |
p = rectangle_random(W, H) | |
return p if p[0]/W <= p[1]/H else (W-p[0], H-p[1]) | |
def circle_random(R=5): | |
p = triangle_random(R, R) | |
r = p[1] | |
a = p[0]/p[1] * 2 * math.pi | |
return (r * math.cos(a), r * math.sin(a)) | |
def random_points_array(point_func, number=5000): | |
return [point_func() for _ in xrange(number)] | |
def plot_array(points): | |
import matplotlib.pyplot as plt | |
plt.plot([p[0] for p in points], [p[1] for p in points], 'ro') | |
plt.show() | |
# | |
plot_array(random_points_array(circle_random)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment