de-buffon-needle/de Buffon.py
2014-01-13 22:01:52 +01:00

76 lines
1.2 KiB
Python

import math
import random
import turtle
#Parameters
X = 100
Y = 100
T = 20
L = 5 / 6 * T
N = 213
axes = ()
def settings():
"""Turtle settings"""
turtle.title("de Buffon's needle")
turtle.setworldcoordinates(-(X + 2), -(Y), X + 2, Y)
turtle.hideturtle()
turtle.speed(0)
def go(x, y):
"""Move cursor to the point (x, y) without drawing a line."""
turtle.pu()
turtle.goto(x, y)
turtle.pd()
def parquet(t):
"""Draw parquet's axes."""
global X, axes
go(-X, -Y)
for x in range(-X, X + 1, t):
axes += x,
turtle.lt(90)
turtle.goto(x, Y)
go(x, -Y)
turtle.rt(90)
go(x + t, -Y)
def needle(l):
"""
Throw a needle.
If it crosses the axes it colors red and returns 1,
otherwise it returns 0.
"""
go(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 axes:
if (x1 < x < x2) or (x2 < x < x1):
turtle.pencolor("red")
turtle.bk(l)
turtle.pencolor("black")
return 1
else:
return 0
settings()
parquet(T)
p = 0
for i in range(N):
p += needle(L)
try:
π = (2 * L) / (T * p / N)
except ZeroDivisionError:
π = 0
print(π)
print("Deviation:", abs(100 - (π / math.pi * 100)), "%")
turtle.mainloop()