2015-06-12 133 views
-1

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

+1

你可以发布你已经做了请的工作? – Sait

+0

你绝对可以使用randint来随机定位你的观点,简单地使用['turtle.dot'](https://docs.python.org/2/library/turtle.html#turtle.dot) – tutuDajuju

+0

是否分配需要统一? –

回答

1

在绘制点之前,您需要确认点实际上位于圆内,(-140,-140)点不在圆内,但可以由(randint(-140,140), randint(-140,140))生成。

这样做的常用方法是循环,直到你得到适合你的限制,你的情况的结果,从(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

一种非易失循环变体:

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

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

enter image description here