开发者

Write a random function without using stl functions

开发者 https://www.devze.com 2023-04-12 17:09 出处:网络
I need a function which can generate random numbers without using the standard library functions. I thought time()%100 would be good but when 开发者_开发技巧you run in a loop, say 10 times, you get th

I need a function which can generate random numbers without using the standard library functions. I thought time()%100 would be good but when 开发者_开发技巧you run in a loop, say 10 times, you get the same value all the time. Is there a better way?


The simplest classical generator is the linear congruent generator. The choice of parameters for it is critical, however; see Random Number Generators: Good Ones Are Hard to Find (Park and Miller, CACM Oct., 1988). Something like:

static int current;         //  Set to arbitrary value by seed
static long long const a = 48271;
static long long const m = 2147483647; 

int
rand()
{
    current = (a * current) % m;
    return current;
}

(This assumes at least 32 bit int's.)


Just implement a simple PRNG, using e.g. the Linear Congruential method - it's only a couple of lines of code.

0

精彩评论

暂无评论...
验证码 换一张
取 消