Created
July 7, 2013 09:25
-
-
Save msalahi/5942914 to your computer and use it in GitHub Desktop.
parallelized monte carlo integration using python 3
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
import concurrent.futures | |
import random | |
def f(x): | |
return x**2 | |
def integrate(func, start, end, num_samples=1000): | |
"""uses random sampling to integrate func from 'start' to 'end'""" | |
with concurrent.futures.ProcessPoolExecutor() as executor: | |
random_samples = (random.uniform(start, end) for i in range(num_samples)) | |
total = sum(executor.map(func, random_samples)) | |
return (end-start) * total /num_samples | |
#Integrate f(x) = x^2 from 0 to 100. Exact answer is 333333.33 | |
print(integrate(f, 0, 100, num_samples=100000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it's a bummer they don't have parallelizable comprehensions