生成 2 个具有特定概率的随机数

Generating 2 random numbers with specific probabilities

我之前编写了一个代码,生成随机数 - 0 或 1 - 表示一次抛掷的结果,假设正面或反面的概率为 0.5“等概率”。

现在我想修改代码,使其代表伯诺利试验。 H - head- 代表一次成功,一个变量p代表成功的概率。 我试图搜索如何以特定概率生成随机数,但我不知道它是如何完成的。

我之前的代码

n = 1; %number of trials

% Generating a random number from 1 to n trials, logical condition <0.5
% indicates that function rand should generates only two outcomes,
% either 0 or 1.

% Let 1 indicates "H" and 0 indicates "T".
x = rand(1,n) <0.5;

% count how many H and T in each tossing trial
number_of_H =0 ; number_of_T  =0;

for n=1:n
    if(x(1,n)==1)
        number_of_H=number_of_H+1;
    end
    if(x(1,n)==0) 
        number_of_T = number_of_T+1;
    end
end

probability_H = number_of_H/n; 
probability_T = number_of_T/n; 

我从 mathwork reference 看到了这个 r = random(pd) 但是当我试图用 pd 替换 0.7 作为概率时它给出了一个错误,这不是概率分布。

你快到了,只是改变

x = rand(1,n) <0.5;

x = rand(1,n) < p;

就是这样。由于 rand 将以相同的概率产生 0 和 1 之间的数字,所有这些值中的 1*p 将低于 p,因此变为 1(真),其余为 >=p 并将变成 0 (False),这正是您要查找的内容。使用 < 还是 <= 并不重要,因为你恰好命中 p 的概率几乎为 0。使用 rand 产生恰好 0 或 1 的概率也是如此。

好吧,有两件事。您不能简单地将 0.7 传递给 randompd 的原因是因为它期望参数是概率分布。不仅仅是一个数字。创建一个概率分布看here

但是你的代码是可以用的!所以目前对于 "fair coin" 它的 .5 和 .5 是令人兴奋的,你在这一行

x = rand(1,n) <0.5;

但对于你知道的有偏见的硬币,你需要更多这样的东西

x = rand(1,n) <0.7;

希望对您有所帮助。也许你从老师或其他人那里得到了密码。但我会解释的。 rand(1,n) 生成一个随机数(从 0 到 1 的均匀分布)说 <0.5 将其转换为逻辑值。真为 1,0 为假。所以现在您已经使用 0.5 作为阈值将统一分布转换为二进制分布。对于您要使用 0.7 作为阈值的加权硬币