Skip to content

Instantly share code, notes, and snippets.

@ncot-tech
Created March 13, 2024 19:38
Show Gist options
  • Save ncot-tech/2f29a6dfb7bc5f955eacdc2770285beb to your computer and use it in GitHub Desktop.
Save ncot-tech/2f29a6dfb7bc5f955eacdc2770285beb to your computer and use it in GitHub Desktop.
Monte-Carlo method for calculating Pi
import pygame
import random
import math
# Initialize Pygame
pygame.init()
# Set up the screen
WIDTH, HEIGHT = 600, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Monte Carlo Pi Approximation")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255,0)
YELLOW = (0, 255, 255)
# Clock
clock = pygame.time.Clock()
# Number of points and points inside the circle
num_points = 0
points_inside_circle = 0
# Main loop
running = True
screen.fill(BLACK)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Generate random point
x = random.uniform(0, 1)
y = random.uniform(0, 1)
# Draw points
#pygame.draw.circle(screen, WHITE, (WIDTH // 2, HEIGHT // 2), WIDTH // 2, 1) # Draw circle
pygame.draw.arc(screen, WHITE, [-WIDTH,-HEIGHT,WIDTH*2,HEIGHT*2], math.radians(-90), math.radians(0), 1)
pygame.draw.rect(screen, YELLOW, (0, 0, WIDTH, HEIGHT), 1) # Draw square
# Check if point is inside the circle
distance = x**2 + y**2
if distance <= 1:
pygame.draw.circle(screen, RED, (int(x * WIDTH), int(y * HEIGHT)), 1) # Draw random point
points_inside_circle += 1
else:
pygame.draw.circle(screen, GREEN, (int(x * WIDTH), int(y * HEIGHT)), 1) # Draw random points
num_points += 1
# Update display
pygame.display.flip()
# Limit frame rate
#clock.tick(60)
if num_points == 100000:
running = False
# Calculate pi approximation
print(f"Points plotted {num_points}, {points_inside_circle} points inside circle")
pi_approximation = 4 * points_inside_circle / num_points
print("Approximation of Pi using Monte Carlo method:", pi_approximation)
# Quit Pygame
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment