10 Random Sampling Solutions
title: "Random Sampling" date: 2026-05-24T13:51:01Z
Random Sampling
1import numpy as np
1np.__version__
'1.11.2'
1__author__ = 'kyubyong. longinglove@nate.com'
Simple random data
Q1. Create an array of shape (3, 2) and populate it with random samples from a uniform distribution over [0, 1).
1np.random.rand(3, 2)
2# Or np.random.random((3,2))
array([[ 0.13879034, 0.71300174],
[ 0.08121322, 0.00393554],
[ 0.02349471, 0.56677474]])
Q2. Create an array of shape (1000, 1000) and populate it with random samples from a standard normal distribution. And verify that the mean and standard deviation is close enough to 0 and 1 repectively.
1out1 = np.random.randn(1000, 1000)
2out2 = np.random.standard_normal((1000, 1000))
3out3 = np.random.normal(loc=0.0, scale=1.0, size=(1000, 1000))
4assert np.allclose(np.mean(out1), np.mean(out2), atol=0.1)
5assert np.allclose(np.mean(out1), np.mean(out3), atol=0.1)
6assert np.allclose(np.std(out1), np.std(out2), atol=0.1)
7assert np.allclose(np.std(out1), np.std(out3), atol=0.1)
8print np.mean(out3)
9print np.std(out1)
-0.00110028519551
0.999683483393
Q3. Create an array of shape (3, 2) and populate it with random integers ranging from 0 to 3 (inclusive) from a discrete uniform distribution.
1np.random.randint(0, 4, (3, 2))
array([[1, 3],
[3, 0],
[0, 0]])
Q4. Extract 1 elements from x randomly such that each of them would be associated with probabilities .3, .5, .2. Then print the result 10 times.
1x = [b'3 out of 10', b'5 out of 10', b'2 out of 10']
1for _ in range(10):
2 print np.random.choice(x, p=[.3, .5, .2])
2 out of 10
5 out of 10
3 out of 10
5 out of 10
5 out of 10
5 out of 10
2 out of 10
2 out of 10
5 out of 10
5 out of 10
Q5. Extract 3 different integers from 0 to 9 randomly with the same probabilities.
1np.random.choice(10, 3, replace=False)
array([5, 4, 0])
Permutations
Q6. Shuffle numbers between 0 and 9 (inclusive).
1x = np.arange(10)
2np.random.shuffle(x)
3print x
[2 3 8 4 5 1 0 6 9 7]
1# Or
2print np.random.permutation(10)
[5 2 7 4 1 0 6 8 9 3]
Random generator
Q7. Assign number 10 to the seed of the random generator so that you can get the same value next time.
1np.random.seed(10)