C 自定义随机函数

non*_*uco 4 c random srand

我想用 C 语言创建一个快速的轻量级函数,它返回一个伪随机无符号字符。对我(一个 ANSI C 程序员)来说,具有挑战性的部分是我不能使用<stdio.h>或任何其他现成的函数。有什么建议..?

“快速”我的意思是:避免不必要的代码(例如 if 语句、循环等)“轻量级”我的意思是:尽可能少地使用变量

谢谢

Vin*_*ura 5

来自 linux 内核源代码 (random32.c)

rnd_state 中的值应初始化为:s1 > 1、s2 > 7、s3 > 15。

该论文声称这是一个基于 GNU Scientific Library 1.5(2004 年 6 月 30 日)代码的最大等分布组合 Tausworthe 生成器

struct rnd_state {
    u32 s1, s2, s3;
};

static u32 __random32(struct rnd_state *state)
{
#define TAUSWORTHE(s,a,b,c,d) ((s&c)<<d) ^ (((s <<a) ^ s)>>b)

    state->s1 = TAUSWORTHE(state->s1, 13, 19, 4294967294UL, 12);
    state->s2 = TAUSWORTHE(state->s2, 2, 25, 4294967288UL, 4);
    state->s3 = TAUSWORTHE(state->s3, 3, 11, 4294967280UL, 17);

    return (state->s1 ^ state->s2 ^ state->s3);
}
Run Code Online (Sandbox Code Playgroud)

学术界:http : //www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps


Pet*_* G. 5

使用线性同余生成器

例如

uint32_t state = 777;

char myRand()
{
   state = state * 1664525 + 1013904223;
   return state >> 24;
}
Run Code Online (Sandbox Code Playgroud)

请注意,myRand返回高位,它们比低位更伪随机。

DH Lehmer 于 1949 年引入了线性同余生成器(参见 Proc. 2nd Symp. on Large-Scale Digital Calculating Machinery (Cambridge, Mass.:Harvard University Press, 1951), 141-146)。我给出的具体数值常数似乎源自 Press, William H.;等。(1992)。Fortran 77 中的数值方法:科学计算的艺术(第 2 版)。ISBN 978-0-521-43064-7。

  • 也许他想产生简单的、低档的 8 位音频噪音,我是谁知道的?一个 LCG 作为一个合理的选择。 (4认同)