### MATLAB Code Examples

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
% MATLAB Code for Coin Toss Simulation r=zeros([100:1]); heads=0; tails=0; rng('default') for j=1:100 r(j)=rand(); if r(j) < 0.5 heads=heads+1 else tails=tails+1 end end heads tails |

### Python Code Examples

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
% Python Code for Coin Toss Simulation import math import numpy as np import random r=np.zeros(100) heads = 0 tails = 0 random.seed(8952) for j in range(100): r[j]=random.random() if r[j] < 0.5: heads = heads+1 else: tails = tails+1 print("heads= ",heads,"tails=" ,tails) |

### Exercises

- Create a model of a pair of dice analogous to the coin model where there is an equal probability for each of the six numbers on each die. Run the model 100 times and make a graph of the resulting distribution. Create a second version where the dice are biased so that there is a 30% greater chance of a six on each die. Compare the two graphs and describe the results.
- Assume there is a hiker who is lost in the forest and is trying to find their way out. A hiker without a compass trying to find their way in the dark can step in any of eight directions (N, NE, E, SE, S, SW, W, NW) with each step. Studies show that people tend to veer to the right under such circumstances. Initially, the hiker is facing north. Suppose at each step probabilities of going in the indicated directions are as follows: N – 19%, NE – 24%, E – 17%, SE – 10%, S – 2%, SW – 3%, W – 10%, NW – 15%. Notice that these probabilities add up to 100%. We are going to construct a random walk simulator that uses the probability and the built-in random number generator in MATLAB and Python. You know that the random number generator provides a uniform distribution of numbers over the range from 0 to 1. This is what will be used in our simulator. For MATLAB users, download the MATLAB script, hikerwalk.m, and two function files Hiker.m and animWalk.m. For Python users download the file hikerwalk.py. These are an implementation of the model we’ve been discussing. The user provides the number of steps and the script will return an animation of the hiker’s random walk, the coordinates of the hiker’s final position and the hiker’s distance from the origin. Run the hikerwalk script using 100 steps. The resulting random walk with be animated in a figure window which is scaled to contain the entire walk.Let’s conduct a number of random walks to identify a search grid for the lost hiker. Using the script, conduct 20 random walks. Record the coordinates of the hiker’s final position and distance from the origin. Plot those results and use them to recommend a search area for the lost hiker.