How do I draw a random dot in a circle in python?

5.4k views Asked by At

So I have my circle drawn already, it has a radius of 140. Should I use r.randint(-140,140) to throw a random dot? and how do I make it seen in the circle(turtle graphic)?

3

There are 3 answers

0
Raniz On

You will need to verify that the point is actually inside your circle before you draw it, the point (-140,-140) isn't inside the circle for example but could be generated by (randint(-140,140), randint(-140,140)).

The common way of doing this is to loop until you get a result that fits your restrictions, in your case that its distance from (0,0) is less than the radius of the circle:

import math, random

def get_random_point(radius):
    while True:
        # Generate the random point
        x = random.randint(-radius, radius)
        y = random.randint(-radius, radius)
        # Check that it is inside the circle
        if math.sqrt(x ** 2 + y ** 2) < radius:
            # Return it
            return (x, y)
0
Amadan On

A non-looping variant:

import math, random, turtle
turtle.radians()
def draw_random_dot(radius):
    # pick random direction
    t = random.random() * 2 * math.pi
    # ensure uniform distribution
    r = 140 * math.sqrt(random.random())
    # draw the dot
    turtle.penup()
    turtle.left(t)
    turtle.forward(r)
    turtle.dot()
    turtle.backward(r)
    turtle.right(t)

for i in xrange(1000): draw_random_dot(140)
0
Alex Ivanov On

It depends on where the beginning of the coordinate system is. If zeros start in the left upper conner of the picture, while loop is needed to make sure that dots are being placed within the circle's boundaries. If xy coordinates start in the center of the circle then the placement of the dots is limited by the circle's radius. I made a script for Cairo. It is not too too off topic. https://rockwoodguelph.wordpress.com/2015/06/12/circle/

enter image description here