3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
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.
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.
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.
22 #include <gsl/gsl_rng.h>
24 /* This is an implementation of the algorithm used in Numerical
25 Recipe's ran2 generator. It is a L'Ecuyer combined recursive
26 generator with a 32-element shuffle-box.
28 As far as I can tell, in general the effects of adding a shuffle
29 box cannot be proven theoretically, so the period of this generator
32 The period of the underlying combined generator is O(2^60). */
34 static inline unsigned long int ran2_get (void *vstate);
35 static double ran2_get_double (void *vstate);
36 static void ran2_set (void *state, unsigned long int s);
38 static const long int m1 = 2147483563, a1 = 40014, q1 = 53668, r1 = 12211;
39 static const long int m2 = 2147483399, a2 = 40692, q2 = 52774, r2 = 3791;
42 #define N_DIV (1 + 2147483562/N_SHUFFLE)
49 unsigned long int shuffle[N_SHUFFLE];
53 static inline unsigned long int
54 ran2_get (void *vstate)
56 ran2_state_t *state = (ran2_state_t *) vstate;
58 const unsigned long int x = state->x;
59 const unsigned long int y = state->y;
62 long int t1 = a1 * (x - h1 * q1) - h1 * r1;
65 long int t2 = a2 * (y - h2 * q2) - h2 * r2;
77 unsigned long int j = state->n / N_DIV;
78 long int delta = state->shuffle[j] - t2;
82 state->shuffle[j] = t1;
89 ran2_get_double (void *vstate)
91 float x_max = 1 - 1.2e-7f ; /* Numerical Recipes version of 1-FLT_EPS */
93 float x = ran2_get (vstate) / 2147483563.0f ;
102 ran2_set (void *vstate, unsigned long int s)
104 ran2_state_t *state = (ran2_state_t *) vstate;
108 s = 1; /* default seed is 1 */
112 for (i = 0; i < 8; i++)
115 long int t = a1 * (s - h * q1) - h * r1;
121 for (i = N_SHUFFLE - 1; i >= 0; i--)
124 long int t = a1 * (s - h * q1) - h * r1;
128 state->shuffle[i] = s;
137 static const gsl_rng_type ran2_type =
139 2147483562, /* RAND_MAX */
141 sizeof (ran2_state_t),
146 const gsl_rng_type *gsl_rng_ran2 = &ran2_type;