以指定概率随机选择两个选项之一

Randomly choosing one of two options with specified probability

我有两个子程序要执行,一个概率为 p1,另一个概率为 p2 s.t。 p1+p2=1,我正在通过以下方法解决问题:

say p1=0.6, p2=0.4, i need to perform the selection between 2 subroutine 10 times
  1. 使用函数:out = randsrc(1,10,[1,2;0.6,0.4]);然后选择输出矩阵1对应的routine 1和输出矩阵2对应的routine 2

这里我得到输出 1: 2 1 2 2 1 2 1 2 1 1 再次执行它给出:1 1 2 2 2 2 1 2 1

预期输出为第 1 次 6 次和第 2 次 4 次,但输出与预期不符。

  1. 使用函数:s = randsample([1,2],10,true,[0.6,0.4]);
  2. 使用例程:

    s=[]; for i=1:10 c = rand if c<=0.6 select = 2; else select = 1; end s = [s,select]; end

方法二和方法三的结果和方法一一样,谁能帮我找出原因?或者将结果解释为它们是如何遵循概率的?或者其他一些可能的方法来解决这个问题。

我想 10 个样本不足以代表您期望的 60% / 40% 分布。

投掷10次硬币时,出现5次正面5次反面的概率并不高。

尝试 1000000 个值:

out = randsrc(1, 1000000, [1,2;0.6,0.4]);

现在分布应该非常接近 60% / 40%:

[sum(out==1), sum(out==2)]
ans =

      599709      400291

您也可以使用 rand:

x = rand(1, 1000000);
[sum(x <= 0.6), sum(x > 0.6)]
ans =

      600261      399739