3

Suppose I want to create a sample of N elements chosen from [1,2,3] such that 1, 2 and 3 will be represented with weights 0.4,0.4 and 0.2 respectively. How would I do this.

I know how to do it in R without using loops:

mySample <- sample(c(1,2,3),size = 100,replace=T,prob = c(.4,.4,.2))
kthouz
  • 411
  • 7
  • 16

1 Answers1

3

You can generate a random number in [0,1) then if it is in [0,.4) pick "1", else if it is in [.4,.8) pick "2" and else pick "3". the code is:

from random import random;

N = 10;
elements = [1,2,3];
weights = [.4, .4 , .2];
samples = range(N);

r = 0;
temp = 0;
for i in range(10):
    r = random();
    temp = 0;
    for j in range(len(elements)):
        temp += weights[j];
        if(temp>r):
            samples[i] = elements[j];
            break;
Dandelion
  • 744
  • 2
  • 13
  • 34