de-buffon-needle/de Buffon.py
2013-03-22 19:51:55 +01:00

59 lines
946 B
Python

import turtle,random,math
X = 100
Y = 100
T = 20
L = 5/6*T
N = 213
assi = ()
def impostazioni():
turtle.title("Ago di Buffon")
turtle.setworldcoordinates(-(X+2), -(Y), X+2, Y)
turtle.hideturtle()
turtle.speed(0)
def vai(x, y):
turtle.pu()
turtle.goto(x,y)
turtle.pd()
def parquet(t):
global X,assi
vai(-X,-Y)
for x in range(-X,X+1,t):
assi += x,
turtle.lt(90)
turtle.goto(x,Y)
vai(x,-Y)
turtle.rt(90)
vai(x+t,-Y)
def ago(l):
vai(random.uniform(-X,X), random.uniform(-Y,Y))
x1 = turtle.xcor()
turtle.lt(random.uniform(0,360))
turtle.fd(l)
x2 = turtle.xcor()
for x in assi:
if (x1 < x < x2) or (x2 < x < x1):
turtle.pencolor("red")
turtle.bk(l)
turtle.pencolor("black")
return 1
return 0
impostazioni()
parquet(T)
p = 0
for i in range(N):
p += ago(L)
try:
π = (2*L)/(T*p/N)
except ZeroDivisionError:
π = 0
print(π)
print("Scarto:",abs(100-(π/math.pi*100)),"%")
turtle.mainloop()