Skip to content

Instantly share code, notes, and snippets.

@msalahi
Created July 7, 2013 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save msalahi/5942914 to your computer and use it in GitHub Desktop.
Save msalahi/5942914 to your computer and use it in GitHub Desktop.
parallelized monte carlo integration using python 3
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))
@cpdean
Copy link

cpdean commented Jul 7, 2013

it's a bummer they don't have parallelizable comprehensions

executer.[func(i) for i in random_samples]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment