mc_pi.py (1456B)
1 import pygame 2 import time 3 import math 4 import random 5 6 pygame.init() 7 8 WIDTH=500 9 HEIGHT=WIDTH 10 11 display = pygame.display.set_mode((WIDTH,HEIGHT)) 12 13 DOTS = 1000 14 DOT_SIZE = 1 15 16 white = (255, 255, 255) 17 red = (255, 0, 0) 18 black = (0, 0, 0) 19 grey = (100,100,100) 20 light_grey = (50,50,50) 21 22 23 def distance(x_1,y_1,x_2,y_2): 24 return math.sqrt(((x_1 - x_2) ** 2) + ((y_1 - y_2) ** 2)) 25 26 positions = [] 27 distances = [] 28 29 while True: 30 for event in pygame.event.get(): 31 if event.type == pygame.QUIT: 32 pygame.quit() 33 quit() 34 35 display.fill(black) 36 37 pygame.draw.circle(display, white, (int(WIDTH/2), int(HEIGHT/2)), WIDTH/2) 38 39 out = 0 40 inside = 0 41 42 for i in range(0,DOTS): 43 pos_x = random.random() * WIDTH 44 pos_y = random.random() * WIDTH 45 pos = (pos_x,pos_y) 46 47 dist = distance(pos_x,pos_y,int(WIDTH/2), int(HEIGHT/2)) 48 49 if dist > WIDTH/2: 50 out += 1 51 else: 52 inside += 1 53 positions.append((pos_x,pos_y)) 54 distances.append(dist) 55 56 for idx in range(0,len(positions)): 57 pos = positions[idx] 58 if distances[idx] > WIDTH/2: 59 pygame.draw.circle(display, white, pos, DOT_SIZE) 60 else: 61 pygame.draw.circle(display, black, pos, DOT_SIZE) 62 63 pygame.display.update() 64 65 percent_in = inside / (inside + out) 66 area_in = percent_in * WIDTH*HEIGHT 67 pi = area_in / ((WIDTH/2) ** 2) 68 69 print(pi) 70 71 time.sleep(.1)