Skip to content

Instantly share code, notes, and snippets.

@cetver
Created December 20, 2021 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cetver/674e51f4d95374ebe09072e887f77823 to your computer and use it in GitHub Desktop.
Save cetver/674e51f4d95374ebe09072e887f77823 to your computer and use it in GitHub Desktop.
import random
import collections
population = [1, 2, 3, 4]
weights = [0.5, 0.25, 0.15, 0.1]
samples = random.choices(population, weights, k=100)
print(collections.Counter(samples))
@afonari
Copy link

afonari commented Dec 20, 2021

import collections
import numpy

population = [1, 2, 3, 4]
weights = [0.5, 0.25, 0.15, 0.1]
nsamples = 1000000
samples = numpy.random.choice(population, nsamples, p=weights)
#samples = random.choices(population, weights, k=nsamples)

counter = collections.Counter(samples)
vals = numpy.array(list(counter.values()), dtype=int)
print(numpy.round(vals / nsamples, 2))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment