📄 randomnr.cpp
字号:
/******************************************************************************* RandomNr.cpp last change: 01/20/1999 version: 0.0.0 design: Eckart Zitzler Paul E. Sevinc implementation: Paul E. Sevinc (c) 1998-1999: Computer Engineering and Networks Laboratory Swiss Federal Institute of Technology Zurich description: See RandomNr.h*******************************************************************************/#include "RandomNr.h"#include <climits>#include <cstddef>#include <ctime>#include "TIKEAFExceptions.h"using namespace std;RandomNr::RandomNr(){ z = static_cast< long >( time( 0 ) ); // see <ctime>}RandomNr::RandomNr( long seed ) : z( seed ){}voidRandomNr::setSeed( long seed ){ z = seed;}doubleRandomNr::uniform01(){// see Reiser, Martin / Wirth, Niklaus.// - Programming in Oberon: Steps beyond Pascal and Modula. const int a = 16807, m = LONG_MAX, // see <climits> - replace by // numeric_limits< long >::max() // when <limits> is available q = m / a, r = m % a; long gamma; gamma = a * ( z % q ) - r * ( z / q ); z = ( gamma > 0 ) ? gamma : ( gamma + m ); return z * ( 1.0 / m );// NOTE: we're in trouble if at some point z becomes -LONG_MAX, 0, or LONG_MAX...}boolRandomNr::flipP( double p ) throw ( ProbabilityException ){#ifndef NOTIKEAFEXCEPTIONS if ( p < 0 || p > 1 ) { throw ProbabilityException( "from RandomNr::flipP" ); }#endif return uniform01() < p ? true : false;}size_tRandomNr::uniform0Max( size_t max ) // exclusive throw ( LimitsException ){#ifndef NOTIKEAFEXCEPTIONS if ( max == 0 ) { throw LimitsException( "from RandomNr::uniform0Max" ); }#endif return static_cast< size_t >( max * uniform01() );}intRandomNr::uniformMinMax( int min, // inclusive int max ) // exclusive throw ( LimitsException ){#ifndef NOTIKEAFEXCEPTIONS if ( min >= max ) { throw LimitsException( "from RandomNr::uniformMinMax" ); }#endif return min >= 0 ? static_cast< int >( min + ( max - min ) * uniform01() ) : static_cast< int >( min - 1 + ( max - min ) * uniform01() );}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -