gpt4 book ai didi

matlab - 创建一个具有偶概率的随机 int 生成器

转载 作者:行者123 更新时间:2023-12-04 15:44:29 24 4
gpt4 key购买 nike

在下面的代码中,我想确保 theImageRand 等于 theImage 或 theImage2 的机会均等,但我意识到等于 2 mod 1 的数字比 2 mod 0 多出 1 到 100 个数字。所以 theImage被选择的时间过多。

这是我想到的最简单的想法,但也许有一个函数可以更轻松地做到这一点?我还想我可以找到一个适合我正在寻找的数字并将其放入 randi(n) 中。

xRand = randi(100);
if mod(xRand,2) == 1
theImageRand = theImage;
elseif mod(xRand,2) == 0
theImageRand = theImage2;
end

如果我能解释得更清楚,请告诉我。提前致谢。

最佳答案

tl;dr

您的代码完全符合您的要求,但可以通过使用 randi(2) 来简化它并删除 mod 的计算。但是,值得解决更多问题......


mod(xRand,2)将 1-100 减少到 0/1

对于xRand 1 到 100 之间,mod(xRand,2) 的结果将在 0 和 1 上均匀分布,如执行以下代码所示:

xRand = 1:100;
xMod = mod(xRand,2);
cnt1 = sum(xMod == 1) % results in 50
cnt0 = sum(xMod == 0) % results in 50 as well

基本上,您的代码按预期工作,因为 randi选择 1 到 100 之间的均匀分布数字。随后,mod将它们简化为二进制表示,由于映射是针对相等的 bin 完成的,因此该表示仍然是均匀分布的。


使用 randi(2) 进行简化

生成这些均匀分布的二进制数的整个过程可以通过从头开始生成一个二进制集来简化。要实现此目的,您可以使用 randi(2)它直接给你 12正如rayryeng 在他对这个问题的评论中指出的那样。
这将为您提供以下代码:

xRand = randi(2);
if xRand == 1
theImageRand = theImage;
elseif xRand == 2
theImageRand = theImage2;
end

正确吗?

现在我们来看看这个问题的有趣部分:结果真的均匀分布吗?为了检查这一点,我们可以运行代码 N次,然后分析每个图像被选择的次数。因此,我们将 1 分配给第一张图像,将 2 分配给第二张图像,并将结果存储在 res 中。 。在 for 循环之后,我们对元素为 1 或 2 的位置求和。

N = 1000000;

theImage = 1;
theImage2 = 2;

res = zeros(N,1);

for n = 1:N
xRand = randi(2);
if xRand == 1
theImageRand = theImage;
elseif xRand == 2
theImageRand = theImage2;
end
% xRand = randi(100);
% if mod(xRand,2) == 1
% theImageRand = theImage;
% elseif mod(xRand,2) == 0
% theImageRand = theImage2;
% end
res(n) = theImageRand;
end

cnt1 = sum(res==1);
cnt2 = sum(res==2);

percentage1 = cnt1/N*100 % approximately 50
percentage2 = cnt2/N*100 % approximately 50 as well

正如我们所见,percentage1 percentage2 大约为 50,这意味着两个图像在大约 50% 的时间内同时被选中。 计算cnt1之间的差异可能会产生误导。和cnt2因为如果N,这个数字可能会很高。很大。但是,如果我们在许多实现中观察到这种差异,则总体平均值将大约为零。此外,我们可以观察到您的代码使用 mod(randi(100),2)也给出了 50% 的分布。它只是不如 randi(2) 的解决方案那么高效和直接。 ,在我使用 R2016a 的计算机上,其执行速度大约提高了 15%。

底线:我建议使用 randi(2)如上所述,因为它更直观且更有效。观察到的差异归因于随机过程,并通过更多的实现来平衡自身。重要的是要考虑两个图像的百分比而不是绝对差异。

关于matlab - 创建一个具有偶概率的随机 int 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38278184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com