71 lines
1.6 KiB
C++
71 lines
1.6 KiB
C++
|
#include <string.h>
|
|||
|
#include <math.h>
|
|||
|
#include <stdlib.h>
|
|||
|
#include "random.h"
|
|||
|
|
|||
|
#define PCRAND
|
|||
|
#ifdef PCRAND
|
|||
|
#define RANDOM_MAX RAND_MAX
|
|||
|
#else
|
|||
|
#define RANDOM_MAX pow(2, 31)-1
|
|||
|
#endif
|
|||
|
|
|||
|
/* this random function returns 1 if a random toss is within pfactor, 0<pfactor<1*/
|
|||
|
int Probability(float pfactor)
|
|||
|
{
|
|||
|
return (pfactor>Random1());
|
|||
|
/* if a random value from 0 to 1 is less than pfactor, return true*/
|
|||
|
}
|
|||
|
/* -----------------------------------------------------------------------------------------------------------------*/
|
|||
|
unsigned Random(unsigned num) /* returns a random word between 0 and num-1*/
|
|||
|
{
|
|||
|
float ratio, temp;
|
|||
|
|
|||
|
ratio=num;
|
|||
|
temp=RANDOM_MAX;
|
|||
|
ratio=ratio/temp;
|
|||
|
#ifdef PCRAND
|
|||
|
temp=rand();
|
|||
|
#else
|
|||
|
temp=random();
|
|||
|
#endif
|
|||
|
if (temp*ratio>num-1) return num-1;
|
|||
|
else return (temp*ratio);
|
|||
|
}
|
|||
|
/* ------------------------------------------------------------------------------------------------------------*/
|
|||
|
/* returns a value between 0 and 1*/
|
|||
|
float Random1(void)
|
|||
|
{
|
|||
|
float ratio,temp;
|
|||
|
|
|||
|
#ifdef PCRAND
|
|||
|
ratio=rand();
|
|||
|
#else
|
|||
|
ratio=random();
|
|||
|
#endif
|
|||
|
temp=RANDOM_MAX;
|
|||
|
ratio=ratio/temp;
|
|||
|
if (ratio<=0) ratio=0.0001;
|
|||
|
if (ratio>=0.9999) ratio=0.9999;
|
|||
|
return ratio;
|
|||
|
}
|
|||
|
/* -------------------------------------------------------------------------------------------------------------------*/
|
|||
|
/* initializes random generator*/
|
|||
|
void InitRandom(int seed)
|
|||
|
{
|
|||
|
#ifdef PCRAND
|
|||
|
srand(seed);
|
|||
|
#else
|
|||
|
static char state[64];
|
|||
|
|
|||
|
initstate(seed,state,64);
|
|||
|
setstate(state);
|
|||
|
#endif
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|