您的位置:首页 > 编程语言 > C语言/C++

关于随机数生成的一些代码(C/C++)

2009-07-24 14:17 363 查看
一、/////////////////////////////////////////////////////////////////////////////
// ELEMENT GDI/DX Game Engine [Version 2002/3/1]
/////////////////////////////////////////////////////////////////////////////
// Original Author : 邱海峰[Southdy]
// OICQ : 359766
// EMAIL: topmud@263.net
/////////////////////////////////////////////////////////////////////////////
// DESCRIPTION :
//
// OTHER : 邱海峰创建于2002/3/1
//
// 使用此随机数生成器者请无条件保留以下版权声明:
// (C) Copyright Beman Dawes 1998. Permission to copy, use, modify, sell and
// distribute this software is granted provided this copyright notice appears
// in all copies. This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
/////////////////////////////////////////////////////////////////////////////
#pragma once
/////////////////////////////////////////////////////////////////////////////
// 包含文件
/////////////////////////////////////////////////////////////////////////////
#include <cassert>
/////////////////////////////////////////////////////////////////////////////
class EK_Rand
{
// 不要有改动这几个常量的想法,否则……打你屁屁!
enum
{
modulus = 2147483647L,
multiplier = 48271L,
validation = 399268537L,
q = modulus / multiplier,
r = modulus % multiplier
};
// 种子数
long value; // 0 < value <= modulus
public:
explicit min_rand( long seed_value=1 ) : value( seed_value )
{
assert( value > 0 && value <= modulus );
}
 

operator long() const { return value; }

double fvalue() const { return double(value) / modulus; }

min_rand& operator=( long new_value )
{
value = new_value;
assert( value > 0 && value <= modulus );
return *this;
}

long operator++()
{
value = multiplier*(value%q) - r*(value/q);
if ( value <= 0 ) value += modulus;
assert( value > 0 && value <= modulus );
return value;
}

long operator++(int) { long temp = value; operator++(); return temp; }

long ten_thousandth() const { return validation; }

long operator()( long n ) { return operator++() % n; }

long operator()() { return operator++(); }

typedef long argument_type;
typedef long result_type;
};
/////////////////////////////////////////////////////////////////////////////

在boost里看到的绝对好东东。
在保留原作者版权声明的条件下可以随意使用 :)

二、

#include <iostream>

#include <ctime>
using namespace std;

class Rand
{
unsigned int seed;
public:
void srand(unsigned int seed){seed = seed;};
unsigned int rand(){seed = seed*1103515245+12345; return (seed>>16)%32768;}
};

int main(int argc, char* argv[])
{
Rand rd;
rd.srand(time(NULL));
for (int i = 0; i < 255; ++i)
cout << rd.rand() << '/t';
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: