如何在python中的圆圈中绘制一个随机点?

时间:2015-06-12 04:32:06

标签: python turtle-graphics

所以我已经绘制了圆圈,它的半径为140.我应该使用r.randint(-140,140)来抛出一个随机点吗?如何在圆圈中看到它(乌龟图形)?

3 个答案:

答案 0 :(得分:1)

在绘制之前,您需要确认该点实际上在您的圆圈内,但(-140,-140)点不在圆圈内,但可以由(randint(-140,140), randint(-140,140))生成。< / p>

执行此操作的常用方法是循环,直到您获得符合限制的结果,在您的情况下,它与(0,0)的距离小于圆的半径:

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)

答案 1 :(得分:1)

非循环变体:

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)

答案 2 :(得分:0)

这取决于坐标系的起点。如果零点从图片的左上方开始,则需要循环以确保将点放置在圆的边界内。如果xy坐标从圆的中心开始,则点的位置受圆的半径限制。我为开罗制作了一个剧本。这不是太偏离主题。 https://rockwoodguelph.wordpress.com/2015/06/12/circle/

enter image description here

相关问题