【问题标题】:How to use the PRNG linear congruential generator for rolling one dice in Matlab如何使用 PRNG 线性同余生成器在 Matlab 中掷骰子
【发布时间】:2025-11-22 10:10:01
【问题描述】:

我必须设计一个线性同余生成器来在 Matlab 中掷骰子。我使用的一般方程是由递归关系定义的:

其中 a,b 和 c 是大的正值。 生成器的结果是向量 R 除以 R 中可能的最大数 (c-1)。

我得到了两组常量 [a,b,c] 并且不知何故,对于下面在我的代码中报告的常量,可以用骰子抛出 0。这不会一直发生,但是当我运行代码时可以说 50% 次。此外,我很少抛出 7,我试图通过“防止抛出 7”这一行来防止这种情况。 奇怪的是,当我使用 a = 1664525、b = 1013904223 和 c = 2^32 时,我没有这些问题。

这怎么可能,我该如何解决?还是和常量有关?

function [out_2] = ThrowDie_2(N,F,a,b,c)
N = 5000; % amount of times the die is thrown
F = 6; % amount of faces of die
a = 3223; 
b = 3323;
c = 3486;
seed = now %Time of the system, the whole part of t corresponds to the date, 
        % and the fractional part corresponds to the time of day. Use
        % format longG to see the decimals. The time of the system will be
        % used as the initial seed for the LCG. 
out_int_2(1) = seed; %The initial value, seed that determines the sequence
    for i=2:N+1
        out_int_2(i) = mod(a.*out_int_2(i-1).*seed+b,c);
        out_2(i) = (out_int_2(i)/(c-1))*F;
        seed = out_2(i);  
    end
if out_2(2:N+1)<=6 ;  %Prevent throwns of 7
  out_2 = ceil(out_2(2:N+1));
else out_2 = round(out_2(2:N+1));
end 
end

【问题讨论】:

  • 代码是什么语言?请编辑并添加相关标签。
  • 在 Matlab 中,抱歉没有提及。
  • 您可能应该向下舍入 (floor) 并添加 1 以避免在输出中出现 0。 round 会导致输出值分布不均。此外,常数的选择会改变各种输出值的概率,选择正确的常数并非易事。

标签: matlab random


【解决方案1】:

Hull-Dobell Theorem 给出了 LCG x -&gt; (a*x+b) mod c 成为最大周期的充分必要条件。其中之一是c 的所有质因数除以a-1。您选择a,b,c 失败了。 7 是 3486 的质因数,它不会除以 3222。因此,您有非零种子,导致零。例如,种子 3310 只需 4 步即可得到 0。

另一方面,我不知道 7 是如何弹出的。我可以复制获取0,但不能复制值&gt;= c。也许关于 Matlab 舍入。

【讨论】:

    最近更新 更多