-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.h
44 lines (35 loc) · 1009 Bytes
/
util.h
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
#ifndef __UTIL_H__
#define __UTIL_H__
#include <stdlib.h>
#include "const.h"
/**
* Return a random int between a and b
* code by theJPester at
* http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range
*/
inline int32_t
rand_int(int32_t min, int32_t max)
{
int32_t r;
const int32_t range = 1 + max - min;
const int32_t buckets = RAND_MAX / range;
const int32_t limit = buckets * range;
/* Create equal size buckets all in a row, then fire randomly towards
* the buckets until you land in one of them. All buckets are equally
* likely. If you land off the end of the line of buckets, try again. */
do
{
r = (int32_t)rand();
} while (r >= limit);
return min + (r / buckets);
}
/**
* Return a random double between a and b
* Straight from the C FAQ http://c-faq.com/lib/fprand.html
*/
inline float64
rand_double(float64 min, float64 max)
{
return min + (rand() / (RAND_MAX /(max-min)));
}
#endif