Skip to content Skip to sidebar Skip to footer

How To Speed Up Monte Carlo Simulation In Python

I have written a poker simulator that calculates the probability to win in texas holdem by running a simulation of games (i.e. monte carlo simulation). Currently it runs around 100

Solution 1:

This algorithm is too long and complex for any sensible suggestion apart from generic ones. So here you go: vectorise everything you can and work with vectors of data instead of loops, lists, insertions, removals. Montecarlo simulations allow for this quite nicely because all samples are independent.

For example, you want 1 million retries, generate a numpy array of random 1 million values in one line. You want to test outcome, place 1 million outcomes into a numpy array and test all of them at once against a given condition generating a numpy array of booleans.

If you manage to vectorize this you will get tremendous performance increases.

Solution 2:

Inefficient array operations are probably causing most of the slowness. In particular, I see a lot of lines like this:

Deck.pop(some_index)

Every time you do that, the list has to shift all the elements after that index. You can eliminate this (as well as repeated random functions) by using:

from random import shuffle

# Setup
originalDeck = createCardDeck()

# Individual run
Deck = originalDeck[:]
shuffle(Deck) # shuffles in place# Draw a card from the end so nothing needs to shift
card = Deck.pop()

# Concise and efficient!

There are some other things you could do, like change long if-else chains into constant time lookups with a dict or custom class. Right now it checks for a straight flush first down to a high card last for every hand, which seems rather inefficient. I doubt that it would make a big difference though.

Post a Comment for "How To Speed Up Monte Carlo Simulation In Python"