1 |
greg |
1.1 |
#ifndef lint |
2 |
greg |
2.10 |
static const char RCSid[] = "$Id: urand.c,v 2.9 2004/05/16 14:49:42 greg Exp $"; |
3 |
greg |
1.1 |
#endif |
4 |
|
|
/* |
5 |
greg |
1.5 |
* Anticorrelated random function due to Christophe Schlick |
6 |
greg |
1.1 |
*/ |
7 |
|
|
|
8 |
greg |
2.6 |
#include "copyright.h" |
9 |
greg |
2.5 |
|
10 |
|
|
#include <stdlib.h> |
11 |
schorsch |
2.7 |
|
12 |
|
|
#include "standard.h" |
13 |
greg |
1.1 |
#include "random.h" |
14 |
|
|
|
15 |
greg |
2.5 |
#undef initurand |
16 |
greg |
1.1 |
|
17 |
gregl |
2.4 |
#define MAXORDER (8*sizeof(unsigned short)) |
18 |
|
|
|
19 |
greg |
2.10 |
static unsigned short empty_tab = 0; |
20 |
|
|
|
21 |
|
|
unsigned short *urperm = &empty_tab; /* urand() permutation */ |
22 |
|
|
int urmask = 0; /* bits used in permutation */ |
23 |
greg |
1.1 |
|
24 |
gregl |
2.3 |
int |
25 |
greg |
1.1 |
initurand(size) /* initialize urand() for size entries */ |
26 |
|
|
int size; |
27 |
|
|
{ |
28 |
|
|
int order, n; |
29 |
|
|
register int i, offset; |
30 |
|
|
|
31 |
greg |
2.10 |
if ((urperm != NULL) & (urperm != &empty_tab)) |
32 |
greg |
2.5 |
free((void *)urperm); |
33 |
|
|
if (--size <= 0) { |
34 |
greg |
2.10 |
empty_tab = 0; |
35 |
|
|
urperm = &empty_tab; |
36 |
greg |
2.5 |
urmask = 0; |
37 |
|
|
return(0); |
38 |
|
|
} |
39 |
greg |
2.8 |
for (i = 1; (size >>= 1); i++) |
40 |
|
|
if (i == MAXORDER) |
41 |
|
|
break; |
42 |
|
|
order = i; |
43 |
|
|
urmask = (1<<order) - 1; |
44 |
gregl |
2.4 |
urperm = (unsigned short *)malloc((urmask+1)*sizeof(unsigned short)); |
45 |
greg |
1.1 |
if (urperm == NULL) { |
46 |
|
|
eputs("out of memory in initurand\n"); |
47 |
|
|
quit(1); |
48 |
|
|
} |
49 |
greg |
2.9 |
urperm[0] = 0; |
50 |
greg |
1.1 |
for (n = 1, offset = 1; n <= order; n++, offset <<= 1) |
51 |
|
|
for (i = offset; i--; ) { |
52 |
greg |
2.8 |
urperm[i+offset] = urperm[i] <<= 1; |
53 |
greg |
1.1 |
if (random() & 0x4000) |
54 |
|
|
urperm[i]++; |
55 |
|
|
else |
56 |
|
|
urperm[i+offset]++; |
57 |
|
|
} |
58 |
greg |
2.8 |
return(urmask+1); |
59 |
greg |
1.2 |
} |
60 |
|
|
|
61 |
|
|
|
62 |
|
|
int |
63 |
greg |
1.3 |
ilhash(d, n) /* hash a set of integer values */ |
64 |
greg |
1.2 |
register int *d; |
65 |
|
|
register int n; |
66 |
|
|
{ |
67 |
greg |
2.10 |
static int tab[8] = {103699,96289,73771,65203,81119,87037,92051,98899}; |
68 |
greg |
1.4 |
register int hval; |
69 |
greg |
1.2 |
|
70 |
|
|
hval = 0; |
71 |
|
|
while (n-- > 0) |
72 |
greg |
2.10 |
hval ^= *d++ * tab[n&7]; |
73 |
|
|
return(hval & 0x7fffffff); |
74 |
greg |
1.1 |
} |