# Day 22 Pre-Class Assignment: Random Numbers#

✅ Put your name here

### Goals for today’s pre-class assignment#

Explore different methods for generating random numbers

Pratice using the

`if`

/`elif`

/`else`

keywords combined with random numbers

The theme of this week is creating and using random numbers to do a wide range of things, such as modeling randomness that naturally needs to be in our models, or using them to solve problems that would otherwise be too difficult to solve.

## Assignment instructions#

**This assignment is due by 7:59pm the day before class,** and should be uploaded into the appropriate “Pre-class assignments” submission folder. Submission instructions can be found at the end of the notebook.

## Revisiting random numbers#

We’ve already been using random numbers in a variety of ways in this course, but the next week or so of material will use random numbers in a number of new modeling contexts. As a reminder of some of the ways we can access random numbers in Python, re-watch the following video:

```
# You are encourage to watch the video in full-screen mode
from IPython.display import YouTubeVideo
YouTubeVideo("fF841G53fGo",width=640,height=360) # random numbers
```

Here are some of the imports we will use in this assignment. Notice that we’re importing both `random`

*and* `numpy`

, which also has a `random`

module. There is also an example for how you can set a specific seed for the `random`

module and the `np.random`

module, which can be useful for testing code to ensure that you understand the results. **Note**: If you want to use a specific seed, you need to make sure the call to the `seed`

function is before the command that is generating the random numbers.

```
import random
import matplotlib.pyplot as plt
import timeit
import numpy as np
import seaborn as sns
sns.set_context('talk')
%matplotlib inline
random.seed(1) # this initializes the seed - see question 6 below
np.random.seed(1)
```

### Practicing random number generation#

The following questions are designed to give you a bit of practice with generating a variety of random numbers. Make sure you are able to accomplish all the tasks included below.

**Question 1**: Write code below to generate 100 random **floats** uniformly distributed between 0 and 1. Plot a histogram of the result values. What happens to your histogram as you generate more values?

```
# Your code here
```

**Question 2**: Generate an array with 100 random **integers** distributed between -1 and 3. Plot a histogram of those values.

```
# your code here
```

**Question 3**: Write code below to generate 10, 100, 1000, and 10000 random floats in the interval \([-5,5]\) and make a histogram for each case. Create a markdown cell after the code and comment on what patterns you see. You might want to try using NumPy’s random module for getting numbers from a uniform distribution for this problem.

**Question 4**: Use NumPy’s `random`

module to produce random numbers from a normal distribution with a mean of 50 and a standard deviation of 20, and generate arrays with 10, 100, 1000, and 10000 samples. Plot the results to see if it converges to a “bell curve” as you increase the number of samples.

**Question 5**:
Broadly across science and engineering you will come across a very wide range of different types of random numbers. We have looked at three different options above:

floats chosen uniformly between two values,

integers chosen uniformly between two values

floats chosen that come from a normal distribution (the so-called “bell curve”)

Next, look through this list of Python’s different choice for distributions and pick three. Make a subplot with one row and three columns that compares the three distributions you chose using 1000 samples for each plot. Label as usual, and put a title that has the name of the distribution.

**Question 6**: As we mentioned in a prior assignment, one of the interesting aspects of random number generators are that they are not **entirely** random! Think about this for a moment: computers are designed to be able to calculate very precise things with very precise instructions - how could one get randomness out of that? If the computer is following precise rules, it will only know to follow exactly those rules the next time. The way it works is that it starts with some number - *which is the seed defined above* - and that generates a sequence; a different seed will generate a different sequence. This is very important: if you want to generate that same sequence again, you can. This means that you can make your code reproducable, which is crucial for testing and debugging your code – often you really don’t want a *truly* random sequence! On the other hand, once you are ready to put your code in use, you can choose something like the current time to generate the seed, and that will be a new and unique sequence.

Your **goal** is to show that specifying a seed will allow you to create reproducible sequence of numbers. To do this, write a short code that uses subplots to make a 2x2 array of plots. For the subplots located at positions [0,0] and [0,1], create a histogram of 1000 random numbers using the same seed (example seed = 456). For the subplots located at positions [1,0] and [1,1], create a histogram of 1000 random numbers using the same seed but different than the first row (example seed = 789). You can use any of the random number generators of your choice (e.g. uniform).

**Question 7**: Explain what this code does.

```
import numpy as np
foo = ['a', 'b', 'c', 'd', 'e']
print(np.random.choice(foo))
```

How would you change the code to choose more than one thing? What if you wanted the choices to be unique?

*Put your answer here*

### A reminder about “elif” statements#

When trying to evaluate conditions to make a decision in your code, sometimes `elif`

is used when there are more than two conditions that we want to check in order to decide how the code behaves. Here is a simple example for how `elif`

can be used. You’ve likely already used `elif`

for code you’ve written, but this should be a nice reminder if you haven’t done it in a while. Note that this simple example doesn’t use `else`

at all – can you think of a way that you might rewrite this in a way that would?

```
import random
x = random.randint(-1,5)
print(x)
if x < 3 and x >-1:
print("too small!")
elif x > 3:
print("too big!")
elif x == 3:
print("perfect!")
elif x == -1:
print("negative?")
```

```
0
too small!
```

**Question 8**: Use a random number generator to simulate the roll of a die (from 1 to 6); then use `if`

/`elif`

/`else`

to sort the outcome. Count how many times 1 appears, how many times 6 appears, and also how many times a non-1 non-6 number appears.
Try this for 100, 1000, 10000 times. Does the number of 1’s and 6’s appear to converge to 1/6 as the number of rolls increases?

Some possibly useful links:

Look up the extra functions associated with the random module

Here are some interesting links on what you use random numbers to do in programming:

### Assignment wrapup#

Please fill out the form that appears when you run the code below. **You must completely fill this out in order to receive credit for the assignment!**

```
from IPython.display import HTML
HTML(
"""
<iframe
src="https://cmse.msu.edu/cmse801-pc-survey"
width="800px"
height="600px"
frameborder="0"
marginheight="0"
marginwidth="0">
Loading...
</iframe>
"""
)
```

### Congratulations, you’re done!#

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Pre-class assignments” folder and upload it there.

See you in class!

© Copyright 2018, Michigan State University Board of Trustees