Simulating a Fun Probability Problem in Python
At school right now, I am taking a course in discrete mathematics. The topic we are on right now is probability. For one of our homeworks, we got the following problem:
We are to choose between two games A, and B. In game A you roll a fair die once and you receive the number of dollars on the top face. In game B you roll two fair dice and you receive the maximum of the two values shown on the top face. It cost $3 dollars to play game A, and $4 to play game B. Which game should we choose?
Now, if I was a better student, I would jump right into the textbook or notes and try to figure out this problem in elegant, mathematical way. Instead of taking that boring route, I wrote a little Python script to simulate this problem. Haters, don't worry. I do know enough about statistics to be confident that if I run these games a whole bunch of times (let's go with 100,000 times) that I will be able to confidently see which of the two games is more profitable.
First I needed a random number generator. Python's standard library includes this and countless other useful libraries that I could drone on about for hours.
Now I need to write a function I can call over and over and over to simulate playing the two games repeatedly. I want to play the two games the same number of times, so let's toss them into a single function called test()
, which will return the net profit of both games for that specific round.
That looks good. Now we need a function that will loop the test over and over and accumulate the total net profit. This function should take the number of times I want to repeat the test as a parameter.
Perfect! Now all we need to do is take the user input asking how many repetitions, run the tests, and report the outcome.
Awesome! All done. Here is the output of the program.
As you can see, it's really easy to get a hack-job answer to a non-obvious probability problem. All you need is a working knowledge of programming, and you're good to go! Python is especially nice for this task because it doesn't require compilation and is, syntactically, very easy to read and write.