2013-08-04 18:48:38 +02:00
|
|
|
import math, random
|
|
|
|
import turtle
|
|
|
|
|
|
|
|
#Parametri
|
2013-01-05 02:59:22 +01:00
|
|
|
|
|
|
|
X = 100
|
|
|
|
Y = 100
|
|
|
|
T = 20
|
2013-08-25 19:41:29 +02:00
|
|
|
L = 5 / 6 * T
|
2013-03-22 19:51:55 +01:00
|
|
|
N = 213
|
2013-01-05 02:59:22 +01:00
|
|
|
|
|
|
|
assi = ()
|
|
|
|
|
2013-08-25 19:41:29 +02:00
|
|
|
|
2013-01-05 02:59:22 +01:00
|
|
|
def impostazioni():
|
2013-08-04 18:48:38 +02:00
|
|
|
"""Impostazioni per inizializzare turtle"""
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.title("Ago di Buffon")
|
2013-08-25 19:41:29 +02:00
|
|
|
turtle.setworldcoordinates(-(X + 2), -(Y), X + 2, Y)
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.hideturtle()
|
|
|
|
turtle.speed(0)
|
|
|
|
|
2013-08-25 19:41:29 +02:00
|
|
|
|
2013-01-05 02:59:22 +01:00
|
|
|
def vai(x, y):
|
2013-08-04 18:48:38 +02:00
|
|
|
"""Sposta il cursore al punto (x, y) senza tracciare una linea."""
|
2013-08-25 19:41:29 +02:00
|
|
|
turtle.pu()
|
2013-08-04 18:48:38 +02:00
|
|
|
turtle.goto(x, y)
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.pd()
|
|
|
|
|
2013-08-25 19:41:29 +02:00
|
|
|
|
2013-01-05 02:59:22 +01:00
|
|
|
def parquet(t):
|
2013-08-04 18:48:38 +02:00
|
|
|
"""Disegna le assi del parquet."""
|
|
|
|
global X, assi
|
|
|
|
vai(-X, -Y)
|
2013-08-25 19:41:29 +02:00
|
|
|
for x in range(-X, X + 1, t):
|
2013-01-05 02:59:22 +01:00
|
|
|
assi += x,
|
|
|
|
turtle.lt(90)
|
2013-08-04 18:48:38 +02:00
|
|
|
turtle.goto(x, Y)
|
|
|
|
vai(x, -Y)
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.rt(90)
|
2013-08-25 19:41:29 +02:00
|
|
|
vai(x + t, -Y)
|
|
|
|
|
2013-01-05 02:59:22 +01:00
|
|
|
|
|
|
|
def ago(l):
|
2013-08-04 18:48:38 +02:00
|
|
|
"""
|
|
|
|
Lancia un'ago.
|
2013-08-25 19:41:29 +02:00
|
|
|
Se incrocia le assi lo colora di rosso e restituisce 1,
|
2013-08-04 18:48:38 +02:00
|
|
|
altrimenti restituisce 0.
|
|
|
|
"""
|
|
|
|
vai(random.uniform(-X, X), random.uniform(-Y, Y))
|
2013-01-05 02:59:22 +01:00
|
|
|
x1 = turtle.xcor()
|
2013-08-04 18:48:38 +02:00
|
|
|
turtle.lt(random.uniform(0, 360))
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.fd(l)
|
|
|
|
x2 = turtle.xcor()
|
|
|
|
for x in assi:
|
2013-08-25 19:41:29 +02:00
|
|
|
if (x1 < x < x2) or (x2 < x < x1):
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.pencolor("red")
|
|
|
|
turtle.bk(l)
|
2013-08-25 19:41:29 +02:00
|
|
|
turtle.pencolor("black")
|
2013-01-05 02:59:22 +01:00
|
|
|
return 1
|
2013-08-04 18:48:38 +02:00
|
|
|
else:
|
|
|
|
return 0
|
2013-08-25 19:41:29 +02:00
|
|
|
|
|
|
|
impostazioni()
|
2013-01-05 02:59:22 +01:00
|
|
|
parquet(T)
|
|
|
|
p = 0
|
|
|
|
for i in range(N):
|
|
|
|
p += ago(L)
|
|
|
|
try:
|
2013-08-25 19:41:29 +02:00
|
|
|
π = (2 * L) / (T * p / N)
|
2013-01-05 02:59:22 +01:00
|
|
|
except ZeroDivisionError:
|
|
|
|
π = 0
|
|
|
|
print(π)
|
2013-08-04 18:48:38 +02:00
|
|
|
|
2013-08-25 19:41:29 +02:00
|
|
|
print("Scarto:", abs(100 - (π / math.pi * 100)), "%")
|
2013-01-05 02:59:22 +01:00
|
|
|
turtle.mainloop()
|