How Computers Generate Random Numbers
Source Code:
rand.h
#ifndef _RAND_H_
#define _RAND_H_
// 函数声明
int rand(void);
void srand(unsigned int seed);
#endif
rand.c
// 包含头文件
#include "rand.h"
// 内部全局变量定义
static unsigned long int next = 1;
// 产生随机数,范围为[0, 0x7FFFFFFF]
int rand(void)
{
#define RAND_A 1103515245
#define RAND_C 12345
#define RAND_M 0x7FFFFFFF
// SEED = (A * SEED + C) mod M;
// rand = f(SEED);
// 1) C is relatively prime to M;
// 2) B = (A - 1) is a multiple of P, for every prime P dividing M;
// 3) B = (A - 1) is a multiple of 4, if M is a multiple of 4.
// Example:
// 1) A = 69069, C = 1, M = 2**32, Used by VMS FORTRAN, VMS BASIC, and others
// 2) A = 65539, C = 0, M = 2**31, Obsolete but still found on some systems
// 3) A = 1103515245, C = 12345, M = 2**15 or 2**31, Used by C and ANSI C
// 4) A = 214013, C = 2531011, M = 2**31, Used by Microsoft C
// 5) A = 134775813, C = 1, M = 2**32, Used by Turbo Pascal
next = (RAND_A * next + RAND_C) & RAND_M;
return (int)next;
}
// 置随机数种子
void srand(unsigned int seed)
{
next = seed;
}
Reference:
http://members.cox.net/srice1/random/random1.html
RockCarry