DNWA/11/wywolania/Data/stide_v1.1/Utils/krand.cc

88 lines
1.6 KiB
C++
Raw Normal View History

2021-01-28 18:33:55 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include "krand.h"
#include <time.h>
#define MBIG 1000000000L
#define MSEED 161803398L
#define FAC (1.0 / MBIG)
static int inext;
static int inextp;
static long ma[56];
double knuth_random(void) {
long mj;
if (++inext == 56) inext = 1;
if (++inextp == 56) inextp = 1;
mj = ma[inext] - ma[inextp];
if (mj < 0) mj += MBIG;
ma[inext] = mj;
return mj * FAC;
}
long seed_random(long seed) {
long mj, mk;
register int i, k;
if (seed < 0) {
time_t tp;
seed = time(&tp);
}
if (seed >= MBIG) {
cerr<<"Seed value too big (> "<<MBIG<<") in knuth_srand().";
exit(1);
}
ma[55] = mj = seed;
mk = 1;
for (i = 1; i <= 54; i++) {
register int ii = (21 * i) % 55;
ma[ii] = mk;
mk = mj - mk;
if (mk < 0) mk += MBIG;
mj = ma[ii];
}
for (k = 0; k < 4; k++) {
for (i = 1; i <= 55; i++) {
ma[i] -= ma[1 + (i + 30) % 55];
if (ma[i] < 0) ma[i] += MBIG;
}
}
inext = 0;
inextp = 31;
return seed;
}
int krandom(int max) {
int retval = (int)(knuth_random() * max);
if (retval < 0 || retval >= max) {
cout<<"ERROR: random num generator out of bounds!"<<endl;
exit(-1);
}
return retval;
}
/*
//for testing
void main(void) {
seed_random(100);
for (int i = 0; i < 24; i++) cout<<i<<" "<<knuth_random()<<" "<<krandom(100)<<endl;
cin.get();
seed_random(200);
for (i = 0; i < 24; i++) cout<<i<<" "<<knuth_random()<<" "<<krandom(100)<<endl;
cin.get();
seed_random(100);
for (i = 0; i < 24; i++) cout<<i<<" "<<knuth_random()<<" "<<krandom(100)<<endl;
cin.get();
}
*/