Skip to content

Instantly share code, notes, and snippets.

@fabian
Created May 18, 2011 23:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabian/979849 to your computer and use it in GitHub Desktop.
Save fabian/979849 to your computer and use it in GitHub Desktop.
Monte Carlo (calculate π using random numbers)
#!/usr/bin/env python
from random import random
from math import pow
from math import sqrt
def pi(sample):
total = 0.0
found = 0.0
for i in range(sample):
x = random()
y = random()
if sqrt(x * x + y * y) <= 1:
found += 1
total += 1
return found / total * 4
# 3.14159...
print pi(10000000)
def integral(sample):
total = 0.0
found = 0.0
for i in range(sample):
x = random()
y = random()
if y <= pow(x, 2):
found += 1
total += 1
return found / total
# 0.3333333...
print integral(10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment