Skip to content

Instantly share code, notes, and snippets.

@hinnerk
Created January 7, 2014 17:03
Show Gist options
  • Save hinnerk/8302546 to your computer and use it in GitHub Desktop.
Save hinnerk/8302546 to your computer and use it in GitHub Desktop.
What's faster, `filter()` or `reduce()`? Find out using a very primitive Monte Carlo search für π.
from random import random
from datetime import datetime
def simulate_dart(x=None):
point_x = random()
point_y = random()
distance = (point_x**2 + point_y**2)**.5 # x**0.5 == sqrt(x)
return (distance < 1) and 1 or 0
def run_simulation_filter(steps=1000000):
hits = filter(simulate_dart,range(steps))
ratio = len(hits) / float(steps)
return ratio * 4
def run_simulation_reduce(steps=1000000):
hits = reduce(lambda acc, n: acc + simulate_dart(), range(steps))
ratio = hits / float(steps)
return ratio * 4
if __name__ == "__main__":
start = datetime.now()
print "Starte Simulation..."
print "Ergebnis: ", run_simulation_filter(1000000000) # filter ist ca. 15% schneller
print "Zeit: ", datetime.now() - start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment