假设我有 100 件物品,我需要将它们分成两组。
选项可以是:
除以 2,所以我正好得到 50 和 50
在 1 到 100 之间选择一个随机数,然后将这个数与其余数分开。
在选项2中,1个项目与50个项目的概率相同(1/100) 但在现实中,我想象一个高斯钟,例如,50 的概率最大,49 和 48 的概率较小,47 和 46 的概率较小,到目前为止。
问题:
如何模拟“随机概率”选择?
在 .NET 6 中是否有任何功能可以做到这一点?
顺便说一下,我在 C# 中工作,但我认为我可以处理这些行,所以这就是为什么我不在这里编写代码,但不编写逻辑。
提前致谢
您可以通过遍历项目集并以概率 p = 0.5 将每个项目分配给集合 1 或集合 2 来实现选项 2。结果集具有 二项分布,B(n=100, p=0.5),这将给出钟形正态分布的离散近似。实际结果会有所不同,但集合计数从 50 变化到 10 以上的可能性很小,这对应于该参数化的 2 个标准偏差。
我不是 C# 用户,所以我不会尝试用您喜欢的语言伪造它,但它非常简单。由于 Python 被广泛使用并且类似于伪代码,这里是该语言的算法:
import random
# create an array with the numbers 1 to 100
values = [i for i in range(1, 101)]
# repeat the following set of operations 10 times...
for replication in range(10):
# create two empty arrays
set1 = []
set2 = []
# Note: random.random() produces float values in the range [0.0, 1.0),
# the probability of getting a value < 0.5 is 1/2
# iterate through each of the values from the array created above
for value in values:
if random.random() < 0.5: # with probability 1/2
set1.append(value) # the value goes in the first set
else:
set2.append(value) # otherwise it goes in the second set
# once all values have been allocated, count how
# many are in each set and print the results
print(len(set1), " : ", len(set2))
产生 10 个拆分,例如:
49 : 51
48 : 52
47 : 53
59 : 41
39 : 61
50 : 50
43 : 57
54 : 46
50 : 50
60 : 40
如果您想偏爱一组,请调整分配的 p 值。通过简单地将条件更改为
if random.random() < 0.7:
你会得到如下结果:
71 : 29
76 : 24
80 : 20
67 : 33
67 : 33
72 : 28
66 : 34
67 : 33
72 : 28
68 : 32