标题:[分享]How Computers Generate Random Numbers
取消只看楼主
RockCarry
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:13
帖 子:662
专家分:58
注 册:2005-8-5
结帖率:95.65%
 问题点数:0 回复次数:0 
[分享]How Computers Generate Random Numbers

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

搜索更多相关主题的帖子: Numbers Random Computers Generate How 
2007-01-11 14:10



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-115419-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.095981 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved