1 /* Copyright (C) 1999,2000,2001, 2003, 2005, 2006, 2009, 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 License
4 * as published by the Free Software Foundation; either version 3 of
5 * the License, or (at your option) any later version.
7 * This library is distributed in the hope that it will be useful, but
8 * 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
20 /* Author: Mikael Djurfeldt <djurfeldt@nada.kth.se> */
26 #include "libguile/_scm.h"
32 #include "libguile/smob.h"
33 #include "libguile/numbers.h"
34 #include "libguile/feature.h"
35 #include "libguile/strings.h"
36 #include "libguile/arrays.h"
37 #include "libguile/srfi-4.h"
38 #include "libguile/vectors.h"
39 #include "libguile/generalized-vectors.h"
41 #include "libguile/validate.h"
42 #include "libguile/random.h"
46 * A plugin interface for RNGs
48 * Using this interface, it is possible for the application to tell
49 * libguile to use a different RNG. This is desirable if it is
50 * necessary to use the same RNG everywhere in the application in
51 * order to prevent interference, if the application uses RNG
52 * hardware, or if the application has special demands on the RNG.
54 * Look in random.h and how the default generator is "plugged in" in
58 scm_t_rng scm_the_rng
;
64 * This is the MWC (Multiply With Carry) random number generator
65 * described by George Marsaglia at the Department of Statistics and
66 * Supercomputer Computations Research Institute, The Florida State
67 * University (http://stat.fsu.edu/~geo).
69 * It uses 64 bits, has a period of 4578426017172946943 (4.6e18), and
70 * passes all tests in the DIEHARD test suite
71 * (http://stat.fsu.edu/~geo/diehard.html)
74 typedef struct scm_t_i_rstate
{
81 #define A 2131995753UL
84 #define M_PI 3.14159265359
88 scm_i_uniform32 (scm_t_rstate
*state
)
90 scm_t_i_rstate
*istate
= (scm_t_i_rstate
*) state
;
91 scm_t_uint64 x
= (scm_t_uint64
) A
* istate
->w
+ istate
->c
;
92 scm_t_uint32 w
= x
& 0xffffffffUL
;
99 scm_i_init_rstate (scm_t_rstate
*state
, const char *seed
, int n
)
101 scm_t_i_rstate
*istate
= (scm_t_i_rstate
*) state
;
105 for (i
= 0; i
< n
; ++i
)
109 w
+= seed
[i
] << (8 * m
);
111 c
+= seed
[i
] << (8 * (m
- 4));
113 if ((w
== 0 && c
== 0) || (w
== -1 && c
== A
- 1))
119 static scm_t_rstate
*
120 scm_i_copy_rstate (scm_t_rstate
*state
)
122 scm_t_rstate
*new_state
;
124 new_state
= scm_gc_malloc_pointerless (scm_the_rng
.rstate_size
,
126 return memcpy (new_state
, state
, scm_the_rng
.rstate_size
);
129 SCM_SYMBOL(scm_i_rstate_tag
, "multiply-with-carry");
132 scm_i_rstate_from_datum (scm_t_rstate
*state
, SCM value
)
133 #define FUNC_NAME "scm_i_rstate_from_datum"
135 scm_t_i_rstate
*istate
= (scm_t_i_rstate
*) state
;
139 SCM_VALIDATE_LIST_COPYLEN (SCM_ARG1
, value
, length
);
140 SCM_ASSERT (length
== 3, value
, SCM_ARG1
, FUNC_NAME
);
141 SCM_ASSERT (scm_is_eq (SCM_CAR (value
), scm_i_rstate_tag
),
142 value
, SCM_ARG1
, FUNC_NAME
);
143 SCM_VALIDATE_UINT_COPY (SCM_ARG1
, SCM_CADR (value
), w
);
144 SCM_VALIDATE_UINT_COPY (SCM_ARG1
, SCM_CADDR (value
), c
);
152 scm_i_rstate_to_datum (scm_t_rstate
*state
)
154 scm_t_i_rstate
*istate
= (scm_t_i_rstate
*) state
;
155 return scm_list_3 (scm_i_rstate_tag
,
156 scm_from_uint32 (istate
->w
),
157 scm_from_uint32 (istate
->c
));
162 * Random number library functions
166 scm_c_make_rstate (const char *seed
, int n
)
170 state
= scm_gc_malloc_pointerless (scm_the_rng
.rstate_size
,
172 state
->reserved0
= 0;
173 scm_the_rng
.init_rstate (state
, seed
, n
);
178 scm_c_rstate_from_datum (SCM datum
)
182 state
= scm_gc_malloc_pointerless (scm_the_rng
.rstate_size
,
184 state
->reserved0
= 0;
185 scm_the_rng
.from_datum (state
, datum
);
190 scm_c_default_rstate ()
191 #define FUNC_NAME "scm_c_default_rstate"
193 SCM state
= SCM_VARIABLE_REF (scm_var_random_state
);
194 if (!SCM_RSTATEP (state
))
195 SCM_MISC_ERROR ("*random-state* contains bogus random state", SCM_EOL
);
196 return SCM_RSTATE (state
);
202 scm_c_uniform01 (scm_t_rstate
*state
)
204 double x
= (double) scm_the_rng
.random_bits (state
) / (double) 0xffffffffUL
;
205 return ((x
+ (double) scm_the_rng
.random_bits (state
))
206 / (double) 0xffffffffUL
);
210 scm_c_normal01 (scm_t_rstate
*state
)
212 if (state
->reserved0
)
214 state
->reserved0
= 0;
215 return state
->reserved1
;
221 r
= sqrt (-2.0 * log (scm_c_uniform01 (state
)));
222 a
= 2.0 * M_PI
* scm_c_uniform01 (state
);
225 state
->reserved1
= r
* cos (a
);
226 state
->reserved0
= 1;
233 scm_c_exp1 (scm_t_rstate
*state
)
235 return - log (scm_c_uniform01 (state
));
238 unsigned char scm_masktab
[256];
241 scm_c_random (scm_t_rstate
*state
, scm_t_uint32 m
)
243 scm_t_uint32 r
, mask
;
247 ? scm_masktab
[m
>> 8] << 8 | 0xff
249 ? scm_masktab
[m
>> 16] << 16 | 0xffff
250 : scm_masktab
[m
>> 24] << 24 | 0xffffff)));
251 while ((r
= scm_the_rng
.random_bits (state
) & mask
) >= m
);
256 SCM scm_c_random_bignum (scm_t_rstate *state, SCM m)
258 Takes a random state (source of random bits) and a bignum m.
259 Returns a bignum b, 0 <= b < m.
261 It does this by allocating a bignum b with as many base 65536 digits
262 as m, filling b with random bits (in 32 bit chunks) up to the most
263 significant 1 in m, and, finally checking if the resultant b is too
264 large (>= m). If too large, we simply repeat the process again. (It
265 is important to throw away all generated random bits if b >= m,
266 otherwise we'll end up with a distorted distribution.)
271 scm_c_random_bignum (scm_t_rstate
*state
, SCM m
)
273 SCM result
= scm_i_mkbig ();
274 const size_t m_bits
= mpz_sizeinbase (SCM_I_BIG_MPZ (m
), 2);
275 /* how many bits would only partially fill the last scm_t_uint32? */
276 const size_t end_bits
= m_bits
% (sizeof (scm_t_uint32
) * SCM_CHAR_BIT
);
277 scm_t_uint32
*random_chunks
= NULL
;
278 const scm_t_uint32 num_full_chunks
=
279 m_bits
/ (sizeof (scm_t_uint32
) * SCM_CHAR_BIT
);
280 const scm_t_uint32 num_chunks
= num_full_chunks
+ ((end_bits
) ? 1 : 0);
282 /* we know the result will be this big */
283 mpz_realloc2 (SCM_I_BIG_MPZ (result
), m_bits
);
286 (scm_t_uint32
*) scm_gc_calloc (num_chunks
* sizeof (scm_t_uint32
),
287 "random bignum chunks");
291 scm_t_uint32
*current_chunk
= random_chunks
+ (num_chunks
- 1);
292 scm_t_uint32 chunks_left
= num_chunks
;
294 mpz_set_ui (SCM_I_BIG_MPZ (result
), 0);
298 /* generate a mask with ones in the end_bits position, i.e. if
299 end_bits is 3, then we'd have a mask of ...0000000111 */
300 const scm_t_uint32 rndbits
= scm_the_rng
.random_bits (state
);
301 int rshift
= (sizeof (scm_t_uint32
) * SCM_CHAR_BIT
) - end_bits
;
302 scm_t_uint32 mask
= ((scm_t_uint32
)-1) >> rshift
;
303 scm_t_uint32 highest_bits
= rndbits
& mask
;
304 *current_chunk
-- = highest_bits
;
310 /* now fill in the remaining scm_t_uint32 sized chunks */
311 *current_chunk
-- = scm_the_rng
.random_bits (state
);
314 mpz_import (SCM_I_BIG_MPZ (result
),
317 sizeof (scm_t_uint32
),
321 /* if result >= m, regenerate it (it is important to regenerate
322 all bits in order not to get a distorted distribution) */
323 } while (mpz_cmp (SCM_I_BIG_MPZ (result
), SCM_I_BIG_MPZ (m
)) >= 0);
324 scm_gc_free (random_chunks
,
325 num_chunks
* sizeof (scm_t_uint32
),
326 "random bignum chunks");
327 return scm_i_normbig (result
);
331 * Scheme level representation of random states.
334 scm_t_bits scm_tc16_rstate
;
337 make_rstate (scm_t_rstate
*state
)
339 SCM_RETURN_NEWSMOB (scm_tc16_rstate
, state
);
344 * Scheme level interface.
347 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")));
349 SCM_DEFINE (scm_random
, "random", 1, 1, 0,
351 "Return a number in [0, N).\n"
353 "Accepts a positive integer or real n and returns a\n"
354 "number of the same type between zero (inclusive) and\n"
355 "N (exclusive). The values returned have a uniform\n"
358 "The optional argument @var{state} must be of the type produced\n"
359 "by @code{seed->random-state}. It defaults to the value of the\n"
360 "variable @var{*random-state*}. This object is used to maintain\n"
361 "the state of the pseudo-random-number generator and is altered\n"
362 "as a side effect of the random operation.")
363 #define FUNC_NAME s_scm_random
365 if (SCM_UNBNDP (state
))
366 state
= SCM_VARIABLE_REF (scm_var_random_state
);
367 SCM_VALIDATE_RSTATE (2, state
);
370 scm_t_uint32 m
= SCM_I_INUM (n
);
371 SCM_ASSERT_RANGE (1, n
, m
> 0);
372 return scm_from_uint32 (scm_c_random (SCM_RSTATE (state
), m
));
374 SCM_VALIDATE_NIM (1, n
);
376 return scm_from_double (SCM_REAL_VALUE (n
)
377 * scm_c_uniform01 (SCM_RSTATE (state
)));
380 SCM_WRONG_TYPE_ARG (1, n
);
381 return scm_c_random_bignum (SCM_RSTATE (state
), n
);
385 SCM_DEFINE (scm_copy_random_state
, "copy-random-state", 0, 1, 0,
387 "Return a copy of the random state @var{state}.")
388 #define FUNC_NAME s_scm_copy_random_state
390 if (SCM_UNBNDP (state
))
391 state
= SCM_VARIABLE_REF (scm_var_random_state
);
392 SCM_VALIDATE_RSTATE (1, state
);
393 return make_rstate (scm_the_rng
.copy_rstate (SCM_RSTATE (state
)));
397 SCM_DEFINE (scm_seed_to_random_state
, "seed->random-state", 1, 0, 0,
399 "Return a new random state using @var{seed}.")
400 #define FUNC_NAME s_scm_seed_to_random_state
403 if (SCM_NUMBERP (seed
))
404 seed
= scm_number_to_string (seed
, SCM_UNDEFINED
);
405 SCM_VALIDATE_STRING (1, seed
);
406 res
= make_rstate (scm_c_make_rstate (scm_i_string_chars (seed
),
407 scm_i_string_length (seed
)));
408 scm_remember_upto_here_1 (seed
);
414 SCM_DEFINE (scm_datum_to_random_state
, "datum->random-state", 1, 0, 0,
416 "Return a new random state using @var{datum}, which should have\n"
417 "been obtailed from @code{random-state->datum}.")
418 #define FUNC_NAME s_scm_datum_to_random_state
420 return make_rstate (scm_c_rstate_from_datum (datum
));
424 SCM_DEFINE (scm_random_state_to_datum
, "random-state->datum", 1, 0, 0,
426 "Return a datum representation of @var{state} that may be\n"
427 "written out and read back with the Scheme reader.")
428 #define FUNC_NAME s_scm_random_state_to_datum
430 SCM_VALIDATE_RSTATE (1, state
);
431 return scm_the_rng
.to_datum (SCM_RSTATE (state
));
435 SCM_DEFINE (scm_random_uniform
, "random:uniform", 0, 1, 0,
437 "Return a uniformly distributed inexact real random number in\n"
439 #define FUNC_NAME s_scm_random_uniform
441 if (SCM_UNBNDP (state
))
442 state
= SCM_VARIABLE_REF (scm_var_random_state
);
443 SCM_VALIDATE_RSTATE (1, state
);
444 return scm_from_double (scm_c_uniform01 (SCM_RSTATE (state
)));
448 SCM_DEFINE (scm_random_normal
, "random:normal", 0, 1, 0,
450 "Return an inexact real in a normal distribution. The\n"
451 "distribution used has mean 0 and standard deviation 1. For a\n"
452 "normal distribution with mean m and standard deviation d use\n"
453 "@code{(+ m (* d (random:normal)))}.")
454 #define FUNC_NAME s_scm_random_normal
456 if (SCM_UNBNDP (state
))
457 state
= SCM_VARIABLE_REF (scm_var_random_state
);
458 SCM_VALIDATE_RSTATE (1, state
);
459 return scm_from_double (scm_c_normal01 (SCM_RSTATE (state
)));
464 vector_scale_x (SCM v
, double c
)
467 if (scm_is_simple_vector (v
))
469 n
= SCM_SIMPLE_VECTOR_LENGTH (v
);
471 SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v
, n
)) *= c
;
475 /* must be a f64vector. */
476 scm_t_array_handle handle
;
481 elts
= scm_f64vector_writable_elements (v
, &handle
, &len
, &inc
);
483 for (i
= 0; i
< len
; i
++, elts
+= inc
)
486 scm_array_handle_release (&handle
);
491 vector_sum_squares (SCM v
)
495 if (scm_is_simple_vector (v
))
497 n
= SCM_SIMPLE_VECTOR_LENGTH (v
);
500 x
= SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v
, n
));
506 /* must be a f64vector. */
507 scm_t_array_handle handle
;
512 elts
= scm_f64vector_elements (v
, &handle
, &len
, &inc
);
514 for (i
= 0; i
< len
; i
++, elts
+= inc
)
520 scm_array_handle_release (&handle
);
525 /* For the uniform distribution on the solid sphere, note that in
526 * this distribution the length r of the vector has cumulative
527 * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
528 * generated as r=u^(1/n).
530 SCM_DEFINE (scm_random_solid_sphere_x
, "random:solid-sphere!", 1, 1, 0,
532 "Fills @var{vect} with inexact real random numbers the sum of\n"
533 "whose squares is less than 1.0. Thinking of @var{vect} as\n"
534 "coordinates in space of dimension @var{n} @math{=}\n"
535 "@code{(vector-length @var{vect})}, the coordinates are\n"
536 "uniformly distributed within the unit @var{n}-sphere.")
537 #define FUNC_NAME s_scm_random_solid_sphere_x
539 if (SCM_UNBNDP (state
))
540 state
= SCM_VARIABLE_REF (scm_var_random_state
);
541 SCM_VALIDATE_RSTATE (2, state
);
542 scm_random_normal_vector_x (v
, state
);
544 pow (scm_c_uniform01 (SCM_RSTATE (state
)),
545 1.0 / scm_c_generalized_vector_length (v
))
546 / sqrt (vector_sum_squares (v
)));
547 return SCM_UNSPECIFIED
;
551 SCM_DEFINE (scm_random_hollow_sphere_x
, "random:hollow-sphere!", 1, 1, 0,
553 "Fills vect with inexact real random numbers\n"
554 "the sum of whose squares is equal to 1.0.\n"
555 "Thinking of vect as coordinates in space of\n"
556 "dimension n = (vector-length vect), the coordinates\n"
557 "are uniformly distributed over the surface of the\n"
559 #define FUNC_NAME s_scm_random_hollow_sphere_x
561 if (SCM_UNBNDP (state
))
562 state
= SCM_VARIABLE_REF (scm_var_random_state
);
563 SCM_VALIDATE_RSTATE (2, state
);
564 scm_random_normal_vector_x (v
, state
);
565 vector_scale_x (v
, 1 / sqrt (vector_sum_squares (v
)));
566 return SCM_UNSPECIFIED
;
571 SCM_DEFINE (scm_random_normal_vector_x
, "random:normal-vector!", 1, 1, 0,
573 "Fills vect with inexact real random numbers that are\n"
574 "independent and standard normally distributed\n"
575 "(i.e., with mean 0 and variance 1).")
576 #define FUNC_NAME s_scm_random_normal_vector_x
579 scm_t_array_handle handle
;
580 scm_t_array_dim
*dim
;
582 if (SCM_UNBNDP (state
))
583 state
= SCM_VARIABLE_REF (scm_var_random_state
);
584 SCM_VALIDATE_RSTATE (2, state
);
586 scm_generalized_vector_get_handle (v
, &handle
);
587 dim
= scm_array_handle_dims (&handle
);
589 if (scm_is_vector (v
))
591 SCM
*elts
= scm_array_handle_writable_elements (&handle
);
592 for (i
= dim
->lbnd
; i
<= dim
->ubnd
; i
++, elts
+= dim
->inc
)
593 *elts
= scm_from_double (scm_c_normal01 (SCM_RSTATE (state
)));
597 /* must be a f64vector. */
598 double *elts
= scm_array_handle_f64_writable_elements (&handle
);
599 for (i
= dim
->lbnd
; i
<= dim
->ubnd
; i
++, elts
+= dim
->inc
)
600 *elts
= scm_c_normal01 (SCM_RSTATE (state
));
603 scm_array_handle_release (&handle
);
605 return SCM_UNSPECIFIED
;
609 SCM_DEFINE (scm_random_exp
, "random:exp", 0, 1, 0,
611 "Return an inexact real in an exponential distribution with mean\n"
612 "1. For an exponential distribution with mean u use (* u\n"
614 #define FUNC_NAME s_scm_random_exp
616 if (SCM_UNBNDP (state
))
617 state
= SCM_VARIABLE_REF (scm_var_random_state
);
618 SCM_VALIDATE_RSTATE (1, state
);
619 return scm_from_double (scm_c_exp1 (SCM_RSTATE (state
)));
627 /* plug in default RNG */
630 sizeof (scm_t_i_rstate
),
634 scm_i_rstate_from_datum
,
635 scm_i_rstate_to_datum
639 scm_tc16_rstate
= scm_make_smob_type ("random-state", 0);
641 for (m
= 1; m
<= 0x100; m
<<= 1)
642 for (i
= m
>> 1; i
< m
; ++i
)
643 scm_masktab
[i
] = m
- 1;
645 #include "libguile/random.x"
647 scm_add_feature ("random");