1 /* rng/rand.c
2 *
3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 */
19
20 #include <config.h>
21 #include <stdlib.h>
22 #include <gsl/gsl_rng.h>
23
24 /* This is the old BSD rand() generator. The sequence is
25
26 x_{n+1} = (a x_n + c) mod m
27
28 with a = 1103515245, c = 12345 and m = 2^31 = 2147483648. The seed
29 specifies the initial value, x_1.
30
31 The theoretical value of x_{10001} is 1910041713.
32
33 The period of this generator is 2^31.
34
35 The rand() generator is not very good -- the low bits of successive
36 numbers are correlated. */
37
38 static inline unsigned long int rand_get (void *vstate);
39 static double rand_get_double (void *vstate);
40 static void rand_set (void *state, unsigned long int s);
41
42 typedef struct
43 {
44 unsigned long int x;
45 }
46 rand_state_t;
47
48 static inline unsigned long int
rand_get(void * vstate)49 rand_get (void *vstate)
50 {
51 rand_state_t *state = (rand_state_t *) vstate;
52
53 /* The following line relies on unsigned 32-bit arithmetic */
54
55 state->x = (1103515245 * state->x + 12345) & 0x7fffffffUL;
56
57 return state->x;
58 }
59
60 static double
rand_get_double(void * vstate)61 rand_get_double (void *vstate)
62 {
63 return rand_get (vstate) / 2147483648.0 ;
64 }
65
66 static void
rand_set(void * vstate,unsigned long int s)67 rand_set (void *vstate, unsigned long int s)
68 {
69 rand_state_t *state = (rand_state_t *) vstate;
70
71 state->x = s;
72
73 return;
74 }
75
76 static const gsl_rng_type rand_type =
77 {"rand", /* name */
78 0x7fffffffUL, /* RAND_MAX */
79 0, /* RAND_MIN */
80 sizeof (rand_state_t),
81 &rand_set,
82 &rand_get,
83 &rand_get_double};
84
85 const gsl_rng_type *gsl_rng_rand = &rand_type;
86