-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.c
More file actions
79 lines (61 loc) · 1.51 KB
/
random.c
File metadata and controls
79 lines (61 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "random.h"
//typedef unsigned int uint32;
//typedef unsigned long long uint64;
uint32 x[5];
uint32 BRandom() {
uint64 sum;
sum = (uint64)2111111111 * (uint64)x[3] +
(uint64)1492 * (uint64)(x[2]) +
(uint64)1776 * (uint64)(x[1]) +
(uint64)5115 * (uint64)(x[0]) +
(uint64)x[4];
x[3] = x[2]; x[2] = x[1]; x[1] = x[0];
x[4] = (uint32)(sum >> 32); // Carry
x[0] = (uint32)(sum); // Low 32 bits of sum
return x[0];
}
void RandomInit(uint32 seed) {
int i;
uint32 s = seed;
// make random numbers and put them into the buffer
for (i = 0; i < 5; i++) {
s = s * 29943829 - 1;
x[i] = s;
}
// randomize some more
for (i = 0; i<19; i++) BRandom();
}
// returns a random number between 0 and 1:
double Random() {
return (double)BRandom() * (1. / (65536.*65536.));
}
int IRandom(int min, int max) {
int r;
// Output random integer in the interval min <= x <= max
// Relative error on frequencies < 2^-32
if (max <= min) {
if (max == min) return min; else return 0x80000000;
}
// Multiply interval with random and truncate
r = (int)((max - min + 1) * Random()) + min;
if (r > max) r = max;
return r;
}
#if 0
int main()
{
if ((result = fopen("result.txt", "w")) == NULL) {
printf("file was not opened\n"); exit(1);
}
RandomInit(1);
int j = 1;
for (int i = 0; i < 1000; i++) {
int rand = IRandom(0, 100);
if (rand < 1000) /*cout << "_index: " << j++ << " rand num: " << rand << endl;*/
{
fprintf(result, "%d\t%d\n", j++, rand);
}
}
return 0;
}
#endif