2015-06-12 136 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