2017-11-11 123 views
0

我無法弄清楚如何計算圓內圓點的座標。現在我的程序應該計算正方形內圓內的點數,並將其除以總點數。如何在python中使用烏龜圖形找到圓的直徑

import turtle 
import random 


t=turtle.Turtle() 
insideCircleCount = 0 



def square(): 
    for y in range(4): 
     t.forward(200) 
     t.left(90) 


def circle(): 
    t.penup() 
    t.setpos(100,0) 
    t.pendown() 
    t.circle(100) 


def randomDot(): 
    z=int(input("iterations:")) 
    for y in range(z): 
     t.penup() 
     t.pensize(1) 
     x=random.randint(0,200) 
     y=random.randint(0,200) 
     t.goto(x,y) 
     t.pendown() 
     t.dot() 
     insideCircle(x,y) 


def insideCircle(x,y): 
    if ((x*x + y*y)<100): 
     insideCircleCount+=1 



#main 
square() 
circle() 
randomDot() 
print('Dots inside circle account for ', insideCircleCount) 
+0

你需要計算X之間的距離,Y你把'insideCircle'和你的圓心。如果它少於100你在裏面。聞起來像功課要自己解決。 –

回答

0
import turtle 
import random 

t=turtle.Turtle() 
insideCircleCount = 0 

def square(): 
    for y in range(4): 
     t.forward(200) 
     t.left(90) 

def circle(): 
    t.penup() 
    t.setpos(100,0) 
    t.pendown() 
    t.circle(100) 

def randomDot(): 
    z=int(input("iterations:")) 
    for y in range(z): 
     t.penup() 
     t.pensize(1) 
     x=random.randint(0,200) 
     y=random.randint(0,200) 
     t.goto(x,y) 
     t.pendown() 
     t.dot() 
     insideCircle(x,y) 

def insideCircle(x,y): 
    # Here the circle has a offset with center at (100,100) 
    #(x – h)^2 + (y – k)^2 = r2 
    if (((x-100)**2 + (y-100)**2) < 100**2): 
     # you were trying to access a local variable before assignment 
     #this fixes that 
     global insideCircleCount 
     insideCircleCount+=1 

#main 
square() 
circle() 
randomDot() 
print('Dots inside circle account for ', insideCircleCount) 
turtle.mainloop() #stops the window from closing