-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathget_pi.py
More file actions
155 lines (128 loc) · 4.95 KB
/
get_pi.py
File metadata and controls
155 lines (128 loc) · 4.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""
This application calculates pi using a monte carlo method,
and visualizes the results compared to the constant in the
math library
"""
from random import random
from math import sqrt
from math import pi
from collections import deque
from time import clock
import pygame
def calculate_pi(iterations):
"""
Calculates pi using a monte carlo method, returns pi
As the are of a circle is pi * r ^ 2, and the area of
a square is (2 * r) ^ 2, we can calculate pi by estimating
the ratio between points inside a circle and a square where
the circle fits perfectly inside the square.
When this ratio is multiplied by 4, the result is pi.
Arguments:
iterations -- the number of random points generated
"""
# TODO: Replace with an iterator?
points_inside_circle = 0
for _ in range(iterations):
# Generate a random point between (-0.5, -0.5) and (0.5, 0.5)
x_position = random() - 0.5
y_position = random() - 0.5
# Check if point is inside the circle
if sqrt(x_position**2 + y_position**2) <= 0.5:
points_inside_circle += 1
estimated_pi = 4 * points_inside_circle / iterations
return estimated_pi
class PiEstimation:
"""
Class for visualizing and calculating pi
"""
# pylint: disable=too-many-instance-attributes
def __init__(self):
"""
Sets up pygame, and variables used for visualization
DO NOT MODIFY
"""
# Pygame initialization
pygame.init()
self._screen_size = 800
self._screen = pygame.display.set_mode((self._screen_size,
self._screen_size))
self._point = pygame.Surface((1, 5))
self._point.fill((0, 255, 0))
# Variables used for visualization
self._accumulated_error = 0
self._values = deque(maxlen=self._screen_size)
self._time_iteration = clock()
self.print_interval = 100
self.draw_interval = 2
# Calculated pi for the current number of iterations
self.current_iterations = 100
self.current_pi = 0
def mainloop(self):
"""
Continously calculates a more correct value for pi
and draws this on screen, loops forever.
"""
# TODO: Change to use an iterator?
while True:
self.current_pi = calculate_pi(self.current_iterations)
self.current_iterations += 1
self._visualize_results()
def _visualize_results(self):
"""
Accumulate errors and values, draw the screen and print statistics
DO NOT MODIFY
"""
# Accumulate errors
self._accumulated_error += abs(self.current_pi - pi)
# Add most recent pi calculation to the drawing list
self._values.append(self._pi2y(self.current_pi))
# Draw results to screen every 2nd iteration
if self.current_iterations % self.draw_interval == 0:
self._update_screen()
# Print statistics every 100 iterations
if self.current_iterations % self.print_interval == 0:
self._print_statistics()
def _update_screen(self):
"""
Draws the last 800 estimated values for pi, as well as
the reference from math.pi
DO NOT MODIFY
"""
self._screen.fill((0, 0, 0))
# Draw all estimates on the screen
for x_position, y_position in enumerate(self._values):
self._screen.blit(self._point, (x_position, y_position))
# Draw the reference pi value on the screen
pygame.draw.line(self._screen,
(255, 0, 0),
(self._screen_size - 50, self._pi2y(pi)),
(self._screen_size, self._pi2y(pi)),
5)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
final_str = "Final value for pi: {}"
print(final_str.format(self.current_pi))
pygame.quit()
exit()
def _print_statistics(self):
"""
Print statistics to stdout for values between this call
and the previous call to this method.
DO NOT MODIFY
"""
time_passed = clock() - self._time_iteration
output = "At iteration {:>6}, pi is {:>6.5}, average error is {:<8.5}, " \
"done in {:<4.2} seconds ({} iterations per second)"
print(output.format(self.current_iterations,
self.current_pi,
self._accumulated_error/self.print_interval,
time_passed,
int(self.print_interval/time_passed)))
self._accumulated_error = 0
self._time_iteration = clock()
def _pi2y(self, value):
# Do not modify this method
return int((value - 2.5) * (self._screen_size * 0.75))
if __name__ == "__main__":
PiEstimation().mainloop()