de-buffon-needle/de Buffon.py

72 lines
1.2 KiB
Python
Raw Normal View History

import math, random
import turtle
#Parametri
2013-01-05 02:59:22 +01:00
X = 100
Y = 100
T = 20
L = 5/6*T
2013-03-22 19:51:55 +01:00
N = 213
2013-01-05 02:59:22 +01:00
assi = ()
def impostazioni():
"""Impostazioni per inizializzare turtle"""
2013-01-05 02:59:22 +01:00
turtle.title("Ago di Buffon")
turtle.setworldcoordinates(-(X+2), -(Y), X+2, Y)
turtle.hideturtle()
turtle.speed(0)
def vai(x, y):
"""Sposta il cursore al punto (x, y) senza tracciare una linea."""
2013-01-05 02:59:22 +01:00
turtle.pu()
turtle.goto(x, y)
2013-01-05 02:59:22 +01:00
turtle.pd()
def parquet(t):
"""Disegna le assi del parquet."""
global X, assi
vai(-X, -Y)
for x in range(-X, X+1, t):
2013-01-05 02:59:22 +01:00
assi += x,
turtle.lt(90)
turtle.goto(x, Y)
vai(x, -Y)
2013-01-05 02:59:22 +01:00
turtle.rt(90)
vai(x+t, -Y)
2013-01-05 02:59:22 +01:00
def ago(l):
"""
Lancia un'ago.
Se incrocia le assi lo colora di rosso e restituisce 1,
altrimenti restituisce 0.
"""
vai(random.uniform(-X, X), random.uniform(-Y, Y))
2013-01-05 02:59:22 +01:00
x1 = turtle.xcor()
turtle.lt(random.uniform(0, 360))
2013-01-05 02:59:22 +01:00
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
else:
return 0
2013-01-05 02:59:22 +01:00
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)), "%")
2013-01-05 02:59:22 +01:00
turtle.mainloop()