1 /* Copyright (C) 1999,2000,2001, 2003, 2005, 2006, 2010 Free Software Foundation, Inc.
2 * This library is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU Lesser General Public
4 * License as published by the Free Software Foundation; either
5 * version 2.1 of the License, or (at your option) any later version.
7 * This library is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * Lesser General Public License for more details.
12 * You should have received a copy of the GNU Lesser General Public
13 * License along with this library; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 /* Author: Mikael Djurfeldt <djurfeldt@nada.kth.se> */
25 #include "libguile/_scm.h"
31 #include "libguile/smob.h"
32 #include "libguile/numbers.h"
33 #include "libguile/feature.h"
34 #include "libguile/strings.h"
35 #include "libguile/unif.h"
36 #include "libguile/srfi-4.h"
37 #include "libguile/vectors.h"
39 #include "libguile/validate.h"
40 #include "libguile/random.h"
44 * A plugin interface for RNGs
46 * Using this interface, it is possible for the application to tell
47 * libguile to use a different RNG. This is desirable if it is
48 * necessary to use the same RNG everywhere in the application in
49 * order to prevent interference, if the application uses RNG
50 * hardware, or if the application has special demands on the RNG.
52 * Look in random.h and how the default generator is "plugged in" in
56 scm_t_rng scm_the_rng;
62 * This is the MWC (Multiply With Carry) random number generator
63 * described by George Marsaglia at the Department of Statistics and
64 * Supercomputer Computations Research Institute, The Florida State
65 * University (http://stat.fsu.edu/~geo).
67 * It uses 64 bits, has a period of 4578426017172946943 (4.6e18), and
68 * passes all tests in the DIEHARD test suite
69 * (http://stat.fsu.edu/~geo/diehard.html)
72 #define A 2131995753UL
75 #define M_PI 3.14159265359
79 scm_i_uniform32 (scm_t_i_rstate *state)
81 scm_t_uint64 x = (scm_t_uint64) A * state->w + state->c;
82 scm_t_uint32 w = x & 0xffffffffUL;
89 scm_i_init_rstate (scm_t_i_rstate *state, const char *seed, int n)
94 for (i = 0; i < n; ++i)
98 w += seed[i] << (8 * m);
100 c += seed[i] << (8 * (m - 4));
102 if ((w == 0 && c == 0) || (w == -1 && c == A - 1))
109 scm_i_copy_rstate (scm_t_i_rstate *state)
111 scm_t_rstate *new_state = scm_malloc (scm_the_rng.rstate_size);
112 return memcpy (new_state, state, scm_the_rng.rstate_size);
117 * Random number library functions
121 scm_c_make_rstate (const char *seed, int n)
123 scm_t_rstate *state = scm_malloc (scm_the_rng.rstate_size);
124 state->reserved0 = 0;
125 scm_the_rng.init_rstate (state, seed, n);
131 scm_c_default_rstate ()
132 #define FUNC_NAME "scm_c_default_rstate"
134 SCM state = SCM_VARIABLE_REF (scm_var_random_state);
135 if (!SCM_RSTATEP (state))
136 SCM_MISC_ERROR ("*random-state* contains bogus random state", SCM_EOL);
137 return SCM_RSTATE (state);
143 scm_c_uniform01 (scm_t_rstate *state)
145 double x = (double) scm_the_rng.random_bits (state) / (double) 0xffffffffUL;
146 return ((x + (double) scm_the_rng.random_bits (state))
147 / (double) 0xffffffffUL);
151 scm_c_normal01 (scm_t_rstate *state)
153 if (state->reserved0)
155 state->reserved0 = 0;
156 return state->reserved1;
162 r = sqrt (-2.0 * log (scm_c_uniform01 (state)));
163 a = 2.0 * M_PI * scm_c_uniform01 (state);
166 state->reserved1 = r * cos (a);
167 state->reserved0 = 1;
174 scm_c_exp1 (scm_t_rstate *state)
176 return - log (scm_c_uniform01 (state));
179 unsigned char scm_masktab[256];
181 static inline scm_t_uint32
182 scm_i_mask32 (scm_t_uint32 m)
187 ? scm_masktab[m >> 8] << 8 | 0xff
189 ? scm_masktab[m >> 16] << 16 | 0xffff
190 : scm_masktab[m >> 24] << 24 | 0xffffff)));
194 scm_c_random32 (scm_t_rstate *state, scm_t_uint32 m)
196 scm_t_uint32 r, mask = scm_i_mask32 (m);
197 while ((r = scm_the_rng.random_bits (state) & mask) >= m);
201 /* Returns 32 random bits. */
203 scm_c_random (scm_t_rstate *state, unsigned long m)
205 return scm_c_random32 (state, (scm_t_uint32)m);
209 scm_c_random64 (scm_t_rstate *state, scm_t_uint64 m)
214 if (m <= SCM_T_UINT32_MAX)
215 return scm_c_random32 (state, (scm_t_uint32) m);
217 mask = scm_i_mask32 (m >> 32);
218 while ((r = ((scm_t_uint64) (scm_the_rng.random_bits (state) & mask) << 32)
219 | scm_the_rng.random_bits (state)) >= m)
225 SCM scm_c_random_bignum (scm_t_rstate *state, SCM m)
227 Takes a random state (source of random bits) and a bignum m.
228 Returns a bignum b, 0 <= b < m.
230 It does this by allocating a bignum b with as many base 65536 digits
231 as m, filling b with random bits (in 32 bit chunks) up to the most
232 significant 1 in m, and, finally checking if the resultant b is too
233 large (>= m). If too large, we simply repeat the process again. (It
234 is important to throw away all generated random bits if b >= m,
235 otherwise we'll end up with a distorted distribution.)
240 scm_c_random_bignum (scm_t_rstate *state, SCM m)
242 SCM result = scm_i_mkbig ();
243 const size_t m_bits = mpz_sizeinbase (SCM_I_BIG_MPZ (m), 2);
244 /* how many bits would only partially fill the last u32? */
245 const size_t end_bits = m_bits % (sizeof (scm_t_uint32) * SCM_CHAR_BIT);
246 scm_t_uint32 *random_chunks = NULL;
247 const scm_t_uint32 num_full_chunks =
248 m_bits / (sizeof (scm_t_uint32) * SCM_CHAR_BIT);
249 const scm_t_uint32 num_chunks = num_full_chunks + ((end_bits) ? 1 : 0);
251 /* we know the result will be this big */
252 mpz_realloc2 (SCM_I_BIG_MPZ (result), m_bits);
255 (scm_t_uint32 *) scm_gc_calloc (num_chunks * sizeof (scm_t_uint32),
256 "random bignum chunks");
260 scm_t_uint32 *current_chunk = random_chunks + (num_chunks - 1);
261 scm_t_uint32 chunks_left = num_chunks;
263 mpz_set_ui (SCM_I_BIG_MPZ (result), 0);
267 /* generate a mask with ones in the end_bits position, i.e. if
268 end_bits is 3, then we'd have a mask of ...0000000111 */
269 const unsigned long rndbits = scm_the_rng.random_bits (state);
270 int rshift = (sizeof (scm_t_uint32) * SCM_CHAR_BIT) - end_bits;
271 scm_t_uint32 mask = 0xffffffff >> rshift;
272 scm_t_uint32 highest_bits = ((scm_t_uint32) rndbits) & mask;
273 *current_chunk-- = highest_bits;
279 /* now fill in the remaining scm_t_uint32 sized chunks */
280 *current_chunk-- = scm_the_rng.random_bits (state);
283 mpz_import (SCM_I_BIG_MPZ (result),
286 sizeof (scm_t_uint32),
290 /* if result >= m, regenerate it (it is important to regenerate
291 all bits in order not to get a distorted distribution) */
292 } while (mpz_cmp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (m)) >= 0);
293 scm_gc_free (random_chunks,
294 num_chunks * sizeof (scm_t_uint32),
295 "random bignum chunks");
296 return scm_i_normbig (result);
300 * Scheme level representation of random states.
303 scm_t_bits scm_tc16_rstate;
306 make_rstate (scm_t_rstate *state)
308 SCM_RETURN_NEWSMOB (scm_tc16_rstate, state);
312 rstate_free (SCM rstate)
314 free (SCM_RSTATE (rstate));
319 * Scheme level interface.
322 SCM_GLOBAL_VARIABLE_INIT (scm_var_random_state, "*random-state*", scm_seed_to_random_state (scm_from_locale_string ("URL:http://stat.fsu.edu/~geo/diehard.html")));
324 SCM_DEFINE (scm_random, "random", 1, 1, 0,
326 "Return a number in [0, N).\n"
328 "Accepts a positive integer or real n and returns a\n"
329 "number of the same type between zero (inclusive) and\n"
330 "N (exclusive). The values returned have a uniform\n"
333 "The optional argument @var{state} must be of the type produced\n"
334 "by @code{seed->random-state}. It defaults to the value of the\n"
335 "variable @var{*random-state*}. This object is used to maintain\n"
336 "the state of the pseudo-random-number generator and is altered\n"
337 "as a side effect of the random operation.")
338 #define FUNC_NAME s_scm_random
340 if (SCM_UNBNDP (state))
341 state = SCM_VARIABLE_REF (scm_var_random_state);
342 SCM_VALIDATE_RSTATE (2, state);
345 unsigned long m = (unsigned long) SCM_I_INUM (n);
346 SCM_ASSERT_RANGE (1, n, SCM_I_INUM (n) > 0);
347 #if SCM_SIZEOF_UNSIGNED_LONG <= 4
348 return scm_from_uint32 (scm_c_random (SCM_RSTATE (state),
350 #elif SCM_SIZEOF_UNSIGNED_LONG <= 8
351 return scm_from_uint64 (scm_c_random64 (SCM_RSTATE (state),
354 #error "Cannot deal with this platform's unsigned long size"
357 SCM_VALIDATE_NIM (1, n);
359 return scm_from_double (SCM_REAL_VALUE (n)
360 * scm_c_uniform01 (SCM_RSTATE (state)));
363 SCM_WRONG_TYPE_ARG (1, n);
364 return scm_c_random_bignum (SCM_RSTATE (state), n);
368 SCM_DEFINE (scm_copy_random_state, "copy-random-state", 0, 1, 0,
370 "Return a copy of the random state @var{state}.")
371 #define FUNC_NAME s_scm_copy_random_state
373 if (SCM_UNBNDP (state))
374 state = SCM_VARIABLE_REF (scm_var_random_state);
375 SCM_VALIDATE_RSTATE (1, state);
376 return make_rstate (scm_the_rng.copy_rstate (SCM_RSTATE (state)));
380 SCM_DEFINE (scm_seed_to_random_state, "seed->random-state", 1, 0, 0,
382 "Return a new random state using @var{seed}.")
383 #define FUNC_NAME s_scm_seed_to_random_state
386 if (SCM_NUMBERP (seed))
387 seed = scm_number_to_string (seed, SCM_UNDEFINED);
388 SCM_VALIDATE_STRING (1, seed);
389 res = make_rstate (scm_c_make_rstate (scm_i_string_chars (seed),
390 scm_i_string_length (seed)));
391 scm_remember_upto_here_1 (seed);
397 SCM_DEFINE (scm_random_uniform, "random:uniform", 0, 1, 0,
399 "Return a uniformly distributed inexact real random number in\n"
401 #define FUNC_NAME s_scm_random_uniform
403 if (SCM_UNBNDP (state))
404 state = SCM_VARIABLE_REF (scm_var_random_state);
405 SCM_VALIDATE_RSTATE (1, state);
406 return scm_from_double (scm_c_uniform01 (SCM_RSTATE (state)));
410 SCM_DEFINE (scm_random_normal, "random:normal", 0, 1, 0,
412 "Return an inexact real in a normal distribution. The\n"
413 "distribution used has mean 0 and standard deviation 1. For a\n"
414 "normal distribution with mean m and standard deviation d use\n"
415 "@code{(+ m (* d (random:normal)))}.")
416 #define FUNC_NAME s_scm_random_normal
418 if (SCM_UNBNDP (state))
419 state = SCM_VARIABLE_REF (scm_var_random_state);
420 SCM_VALIDATE_RSTATE (1, state);
421 return scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
426 vector_scale_x (SCM v, double c)
429 if (scm_is_simple_vector (v))
431 n = SCM_SIMPLE_VECTOR_LENGTH (v);
433 SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v, n)) *= c;
437 /* must be a f64vector. */
438 scm_t_array_handle handle;
443 elts = scm_f64vector_writable_elements (v, &handle, &len, &inc);
445 for (i = 0; i < len; i++, elts += inc)
448 scm_array_handle_release (&handle);
453 vector_sum_squares (SCM v)
457 if (scm_is_simple_vector (v))
459 n = SCM_SIMPLE_VECTOR_LENGTH (v);
462 x = SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v, n));
468 /* must be a f64vector. */
469 scm_t_array_handle handle;
474 elts = scm_f64vector_elements (v, &handle, &len, &inc);
476 for (i = 0; i < len; i++, elts += inc)
482 scm_array_handle_release (&handle);
487 /* For the uniform distribution on the solid sphere, note that in
488 * this distribution the length r of the vector has cumulative
489 * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
490 * generated as r=u^(1/n).
492 SCM_DEFINE (scm_random_solid_sphere_x, "random:solid-sphere!", 1, 1, 0,
494 "Fills @var{vect} with inexact real random numbers the sum of\n"
495 "whose squares is less than 1.0. Thinking of @var{vect} as\n"
496 "coordinates in space of dimension @var{n} @math{=}\n"
497 "@code{(vector-length @var{vect})}, the coordinates are\n"
498 "uniformly distributed within the unit @var{n}-sphere.")
499 #define FUNC_NAME s_scm_random_solid_sphere_x
501 if (SCM_UNBNDP (state))
502 state = SCM_VARIABLE_REF (scm_var_random_state);
503 SCM_VALIDATE_RSTATE (2, state);
504 scm_random_normal_vector_x (v, state);
506 pow (scm_c_uniform01 (SCM_RSTATE (state)),
507 1.0 / scm_c_generalized_vector_length (v))
508 / sqrt (vector_sum_squares (v)));
509 return SCM_UNSPECIFIED;
513 SCM_DEFINE (scm_random_hollow_sphere_x, "random:hollow-sphere!", 1, 1, 0,
515 "Fills vect with inexact real random numbers\n"
516 "the sum of whose squares is equal to 1.0.\n"
517 "Thinking of vect as coordinates in space of\n"
518 "dimension n = (vector-length vect), the coordinates\n"
519 "are uniformly distributed over the surface of the\n"
521 #define FUNC_NAME s_scm_random_hollow_sphere_x
523 if (SCM_UNBNDP (state))
524 state = SCM_VARIABLE_REF (scm_var_random_state);
525 SCM_VALIDATE_RSTATE (2, state);
526 scm_random_normal_vector_x (v, state);
527 vector_scale_x (v, 1 / sqrt (vector_sum_squares (v)));
528 return SCM_UNSPECIFIED;
533 SCM_DEFINE (scm_random_normal_vector_x, "random:normal-vector!", 1, 1, 0,
535 "Fills vect with inexact real random numbers that are\n"
536 "independent and standard normally distributed\n"
537 "(i.e., with mean 0 and variance 1).")
538 #define FUNC_NAME s_scm_random_normal_vector_x
541 scm_t_array_handle handle;
542 scm_t_array_dim *dim;
544 if (SCM_UNBNDP (state))
545 state = SCM_VARIABLE_REF (scm_var_random_state);
546 SCM_VALIDATE_RSTATE (2, state);
548 scm_generalized_vector_get_handle (v, &handle);
549 dim = scm_array_handle_dims (&handle);
551 if (scm_is_vector (v))
553 SCM *elts = scm_array_handle_writable_elements (&handle);
554 for (i = dim->lbnd; i <= dim->ubnd; i++, elts += dim->inc)
555 *elts = scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
559 /* must be a f64vector. */
560 double *elts = scm_array_handle_f64_writable_elements (&handle);
561 for (i = dim->lbnd; i <= dim->ubnd; i++, elts += dim->inc)
562 *elts = scm_c_normal01 (SCM_RSTATE (state));
565 scm_array_handle_release (&handle);
567 return SCM_UNSPECIFIED;
571 SCM_DEFINE (scm_random_exp, "random:exp", 0, 1, 0,
573 "Return an inexact real in an exponential distribution with mean\n"
574 "1. For an exponential distribution with mean u use (* u\n"
576 #define FUNC_NAME s_scm_random_exp
578 if (SCM_UNBNDP (state))
579 state = SCM_VARIABLE_REF (scm_var_random_state);
580 SCM_VALIDATE_RSTATE (1, state);
581 return scm_from_double (scm_c_exp1 (SCM_RSTATE (state)));
589 /* plug in default RNG */
592 sizeof (scm_t_i_rstate),
593 (unsigned long (*)()) scm_i_uniform32,
594 (void (*)()) scm_i_init_rstate,
595 (scm_t_rstate *(*)()) scm_i_copy_rstate
599 scm_tc16_rstate = scm_make_smob_type ("random-state", 0);
600 scm_set_smob_free (scm_tc16_rstate, rstate_free);
602 for (m = 1; m <= 0x100; m <<= 1)
603 for (i = m >> 1; i < m; ++i)
604 scm_masktab[i] = m - 1;
606 #include "libguile/random.x"
608 scm_add_feature ("random");