Created
May 18, 2011 23:45
-
-
Save fabian/979849 to your computer and use it in GitHub Desktop.
Monte Carlo (calculate π using random numbers)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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