Appendix 2: Random Integer Generator
"A random number generator, generates a sequence of numbers or symbols that cannot be reasonably predicted better than by a random chance." Wikipedia
To randomly generate integers between and , inclusive, use the following function from the numpy library. Here and are integers.
import numpy as np
np.random.randint(a, b+1, size=n)
The above code returns an array of random integers from to , inclusive. Notice that every time you run the program, it will generate different sets of numbers. To create the same set of random numbers you can add the line np.random.seed(123).
Example: Write a program to randomly select one integer between 1 and 10.
- Click
+ Code - Type
import numpy as np - Type
np.random.randint(1,10+1,size=1) - Click
playbutton
import numpy as np
np.random.randint(1,10+1,size=1)
Show expected output
array([5])Interpretation: The number 5 is randomly selected from all integers between 1 and 10. If you run this program again, it will, most likely, generate a different result.
Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.