| 1 | /* rng/coveyou.c |
| 2 | * |
| 3 | * This program is free software; you can redistribute it and/or modify |
| 4 | * it under the terms of the GNU General Public License as published by |
| 5 | * the Free Software Foundation; either version 3 of the License, or (at |
| 6 | * your option) any later version. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, but |
| 9 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 | * General Public License for more details. |
| 12 | * |
| 13 | * You should have received a copy of the GNU General Public License |
| 14 | * along with this program; if not, write to the Free Software |
| 15 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 16 | */ |
| 17 | |
| 18 | /* |
| 19 | * This generator is taken from |
| 20 | * |
| 21 | * Donald E. Knuth |
| 22 | * The Art of Computer Programming |
| 23 | * Volume 2 |
| 24 | * Third Edition |
| 25 | * Addison-Wesley |
| 26 | * Section 3.2.2 |
| 27 | * |
| 28 | * This implementation copyright (C) 2001 Carlo Perassi |
| 29 | * and (C) 2003 Heiko Bauke. |
| 30 | * Carlo Perassi reorganized the code to use the rng framework of GSL. |
| 31 | */ |
| 32 | |
| 33 | #include "gsl__config.h" |
| 34 | #include <stdlib.h> |
| 35 | #include "gsl_rng.h" |
| 36 | |
| 37 | #define MM 0xffffffffUL /* 2 ^ 32 - 1 */ |
| 38 | |
| 39 | static inline unsigned long int ran_get (void *vstate); |
| 40 | static double ran_get_double (void *vstate); |
| 41 | static void ran_set (void *state, unsigned long int s); |
| 42 | |
| 43 | typedef struct |
| 44 | { |
| 45 | unsigned long int x; |
| 46 | } |
| 47 | ran_state_t; |
| 48 | |
| 49 | static inline unsigned long int |
| 50 | ran_get (void *vstate) |
| 51 | { |
| 52 | ran_state_t *state = (ran_state_t *) vstate; |
| 53 | |
| 54 | state->x = (state->x * (state->x + 1)) & MM; |
| 55 | |
| 56 | return state->x; |
| 57 | } |
| 58 | |
| 59 | static double |
| 60 | ran_get_double (void *vstate) |
| 61 | { |
| 62 | ran_state_t *state = (ran_state_t *) vstate; |
| 63 | |
| 64 | return ran_get (state) / 4294967296.0; |
| 65 | } |
| 66 | |
| 67 | static void |
| 68 | ran_set (void *vstate, unsigned long int s) |
| 69 | { |
| 70 | ran_state_t *state = (ran_state_t *) vstate; |
| 71 | |
| 72 | unsigned long int diff = ((s % 4UL) - 2UL) % MM; |
| 73 | |
| 74 | if (diff) |
| 75 | state->x = (s - diff) & MM; |
| 76 | else |
| 77 | state->x = s & MM; |
| 78 | |
| 79 | return; |
| 80 | } |
| 81 | |
| 82 | static const gsl_rng_type ran_type = { |
| 83 | "coveyou", /* name */ |
| 84 | MM-1, /* RAND_MAX */ |
| 85 | 2, /* RAND_MIN */ |
| 86 | sizeof (ran_state_t), |
| 87 | &ran_set, |
| 88 | &ran_get, |
| 89 | &ran_get_double |
| 90 | }; |
| 91 | |
| 92 | const gsl_rng_type *gsl_rng_coveyou = &ran_type; |