-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrand.c
63 lines (51 loc) · 1.46 KB
/
rand.c
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
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
// nanohop waits for the monotonic clock to update. Use between calls to
// a random number generator to reduce the chance of duplicate readings at
// the cost of performance
void nanohop() {
struct timespec time;
__pthread_clock_gettime(CLOCK_MONOTONIC,&time);
long time1 = time.tv_nsec,time2 = time.tv_nsec;
while (time1==time2) {
__pthread_clock_gettime(CLOCK_MONOTONIC, &time);
time2=time.tv_nsec;
}
}
// random returns a random number between 0 and 1
float random() {
struct timespec time;
__pthread_clock_gettime(CLOCK_MONOTONIC,&time);
char srand[10];
char fsrand[10];
sprintf( srand, "%ld", time.tv_nsec);
int len=strlen(srand);
if (len>2) {
if (srand[len - 2] == '0') {
srand[len - 2] = '\0';
} else {
if (srand[len - 1] == '0') {
srand[len - 1] = '\0';
}
}
}
strrev(srand);
sprintf(fsrand,"0.%s",srand);
return atof(fsrand);
}
// rnd_ returns a simple random integer between 0 and num inclusive
int rnd_(int num) {
num++;
return num*random();
}
// rnd returns a random integer between 0 and num inclusive
int rnd(int num) {
nanohop();
num++;
float rand=num*random();
int result=rand;
if (rand-result>0.5&&result<num) {result ++;}
return result;
}