以 25% 和 75 的概率生成 0 和 1

generate 0 and 1 with 25% and 75 probability

我在一个网站上看到了以下问题:

 how to  generate 0 and  1  with 25% and  75% probability, here is corresponding code in c++

int rand50()
{
    // rand() function will generate odd or even
    // number with equal probability. If rand()
    // generates odd number, the function will
    // return 1 else it will return 0.
    return rand() & 1;
}
 bool rand75()
{
    return rand50() | rand50();
}

可惜我做不到

>> bitand(rand,1)
Error using bitand
Double inputs must have integer values in the range of ASSUMEDTYPE.

因此我使用了以下算法 1. rand50

function boolean=rand50()

        probability=rand;

        if  probability <=0.5
            boolean=0;
        else
            boolean=1;
        end

        end

2.rand75

function  boolean=rand75()
boolean=bitor(rand50(),rand50());

end

我认为它们是等效的,对吗?或者至少非常接近

rand 在 C/C++ returns 中是一个 整数 而在 MATLAB 中它是 returns 一个 double01 之间。如您所示,您可以构造一个函数,使用 0.5 以相同的概率为您提供 truefalse 的值,尽管它可以缩短为:

function bool = rand50()
    bool = rand() < 0.5;
end

话虽这么说,我想我建议稍微修改一下您的函数以接受一个维度作为输入,这样您就可以一次生成任意数量的随机样本。然后您可以测试输出以确保它符合预期

function bool = rand50(sz)
    bool = rand(sz) < 0.5;
end

function bool = rand75(sz)
    bool = rand50(sz) | rand50(sz);
end

现在我们可以测试一下

samples = rand75([10000, 1]);
mean(samples)
%   0.7460

现在,如果您忽略显示的代码,生成具有给定频率的随机数的更好方法是创建一个函数,在该函数中指定您想要的 0 或 1 的百分比,并使用它来比较 rand

的输出
function bool = myrand(sz, percentage)
    bool = rand(sz) < percentage;
end

% Get 10 samples with 25% 1's
values = myrand([10, 1], 0.25);