Skip to content

Instantly share code, notes, and snippets.

@Dewep
Last active October 9, 2015 18:47
Show Gist options
  • Save Dewep/db682b0549d0238f2b7e to your computer and use it in GitHub Desktop.
Save Dewep/db682b0549d0238f2b7e to your computer and use it in GitHub Desktop.
ApproximationOfPI
from random import uniform
from math import fabs
from sys import argv
interface = len(argv) > 1
if interface:
import turtle
N = 100000000
ran = 1.5
if interface:
turtle.setup(800, 800)
turtle.hideturtle()
turtle.tracer(10000, 25)
hits = 0
x, y = 1, 1
for i in range(1, N + 1):
Dx = uniform(-ran, ran)
Dy = uniform(-ran, ran)
if fabs(x + Dx) < 1 and fabs(y + Dy) < 1:
x += Dx
y += Dy
color = "blue"
if x * x + y * y < 1:
hits = hits + 1
color = "red"
if interface:
if i % 1000 == 0:
turtle.Screen().title("PI: " + str(4 * hits / i))
turtle.penup()
turtle.setposition(int(x * 400), int(y * 400))
turtle.dot(3, color)
elif i % 100 == 0:
print("\b" * 50 + "PI: " + str(4 * hits / i), end="")
if interface:
turtle.Screen().title("PI: " + str(4 * hits / i))
turtle.Screen().exitonclick()
print("PI: " + str(4 * hits / N))
else:
print("\b" * 50 + "PI: " + str(4 * hits / N))
@Toldy
Copy link

Toldy commented Oct 9, 2015

University of Kent; Intellectual Property and licensing <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment