Source From Here
Question
A number selected randomly using a probability distribution will return a number according to the relative weights. For example, a number selected from [1, 2] with relative weights [.9, .1] will have a 90% chance of being 1 and a 10% chance of being 2.
HowTo
USE random.choices() TO SELECT A RANDOM NUMBER
Call random.choices(population, weights) to sample a random number from population based on the probability distribution weights. The weights are relative, meaning the percentage of each number being picked depends on what the weights sum to. e.g.:
Output:
A number selected randomly using a probability distribution will return a number according to the relative weights. For example, a number selected from [1, 2] with relative weights [.9, .1] will have a 90% chance of being 1 and a 10% chance of being 2.
HowTo
USE random.choices() TO SELECT A RANDOM NUMBER
Call random.choices(population, weights) to sample a random number from population based on the probability distribution weights. The weights are relative, meaning the percentage of each number being picked depends on what the weights sum to. e.g.:
- import random
- from collections import defaultdict
- a_list = [1, 2]
- distribution = [.9, .1] # weights add up to 1
- fdict = defaultdict(int)
- loop_num = 1000
- for i in range(loop_num):
- random_number = random.choices(a_list, distribution)[0]
- fdict[random_number] += 1
- for n, f in fdict.items():
- print(f"number {n} appears with probability as {f*100/loop_num}%")
沒有留言:
張貼留言