de-buffon-needle/de Buffon.py

76 lines
1.2 KiB
Python
Raw Permalink Normal View History

2014-01-13 22:01:52 +01:00
import math
import random
import turtle
2014-01-13 22:01:52 +01:00
#Parameters
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
2014-01-13 22:01:52 +01:00
axes = ()
2013-01-05 02:59:22 +01:00
2013-08-25 19:41:29 +02:00
2014-01-13 22:01:52 +01:00
def settings():
"""Turtle settings"""
turtle.title("de Buffon's needle")
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
2014-01-13 22:01:52 +01:00
def go(x, y):
"""Move cursor to the point (x, y) without drawing a line."""
2013-08-25 19:41:29 +02:00
turtle.pu()
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):
2014-01-13 22:01:52 +01:00
"""Draw parquet's axes."""
global X, axes
go(-X, -Y)
2013-08-25 19:41:29 +02:00
for x in range(-X, X + 1, t):
2014-01-13 22:01:52 +01:00
axes += x,
2013-01-05 02:59:22 +01:00
turtle.lt(90)
turtle.goto(x, Y)
2014-01-13 22:01:52 +01:00
go(x, -Y)
2013-01-05 02:59:22 +01:00
turtle.rt(90)
2014-01-13 22:01:52 +01:00
go(x + t, -Y)
2013-08-25 19:41:29 +02:00
2013-01-05 02:59:22 +01:00
2014-01-13 22:01:52 +01:00
def needle(l):
"""
2014-01-13 22:01:52 +01:00
Throw a needle.
If it crosses the axes it colors red and returns 1,
otherwise it returns 0.
"""
2014-01-13 22:01:52 +01:00
go(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()
2014-01-13 22:01:52 +01:00
for x in axes:
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
else:
return 0
2013-08-25 19:41:29 +02:00
2014-01-13 22:01:52 +01:00
settings()
2013-01-05 02:59:22 +01:00
parquet(T)
p = 0
for i in range(N):
2014-01-13 22:01:52 +01:00
p += needle(L)
2013-01-05 02:59:22 +01:00
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(π)
2014-01-13 22:01:52 +01:00
print("Deviation:", abs(100 - (π / math.pi * 100)), "%")
2013-01-05 02:59:22 +01:00
turtle.mainloop()