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.
Example: Write a program to randomly select 3 integers between 1 and 32.
import numpy as np
np.random.randint(1,32+1,size=3)
Show expected output
array([22, 13, 5])Interpretation: 22, 13, and 5 are randomly selected from all integers between 1 and 32.
Example: Write a program to randomly select 10 integers between 1 and 100. Save the result in a variable named x and print x.
import numpy as np
x = np.random.randint(1,100+1,size=10)
x
Show expected output
array([59, 65, 14, 79, 42, 44, 4, 30, 38, 40])Interpretation: The 10 numbers randomly selected from all integers between 1 and 100 are 59, 65, 14, 79, 42, 44, 4, 30, 38, 40.
To get the same result in every run, add np.random.seed(n) where n is any non-negative integer.
Example: Write a program to randomly select 3 integers between 1 and 32. Use the seed number 123.
import numpy as np
np.random.seed(123) # fix seed to get the same result
np.random.randint(1,32+1,size=3)
Show expected output
array([31, 14, 31])Interpretation: The 3 numbers randomly selected with the given seed are 31, 14 and 31.
import numpy as np
np.random.seed(123) # fix seed to get the same result
np.random.randint(1,32+1,size=3)
Show expected output
array([31, 14, 31])Interpretation: By adding np.random.seed(123), we are able to generate the same set of numbers all the time.
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.