1 /* Copyright (C) 1999,2000,2001, 2003 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
81 scm_i_uniform32 (scm_t_i_rstate
*state
)
83 scm_t_int64 x
= (scm_t_int64
) A
* state
->w
+ state
->c
;
84 scm_t_int32 w
= x
& 0xffffffffUL
;
92 /* ww This is a portable version of the same RNG without 64 bit
95 * xx It is only intended to provide identical behaviour on
96 * xx platforms without 8 byte longs or long longs until
97 * xx someone has implemented the routine in assembler code.
103 #define L(x) ((x) & 0xffff)
104 #define H(x) ((x) >> 16)
107 scm_i_uniform32 (scm_t_i_rstate
*state
)
109 scm_t_int32 x1
= L (A
) * L (state
->w
);
110 scm_t_int32 x2
= L (A
) * H (state
->w
);
111 scm_t_int32 x3
= H (A
) * L (state
->w
);
112 scm_t_int32 w
= L (x1
) + L (state
->c
);
113 scm_t_int32 m
= H (x1
) + L (x2
) + L (x3
) + H (state
->c
) + H (w
);
114 scm_t_int32 x4
= H (A
) * H (state
->w
);
115 state
->w
= w
= (L (m
) << 16) + L (w
);
116 state
->c
= H (x2
) + H (x3
) + x4
+ H (m
);
123 scm_i_init_rstate (scm_t_i_rstate
*state
, const char *seed
, int n
)
128 for (i
= 0; i
< n
; ++i
)
132 w
+= seed
[i
] << (8 * m
);
134 c
+= seed
[i
] << (8 * (m
- 4));
136 if ((w
== 0 && c
== 0) || (w
== -1 && c
== A
- 1))
143 scm_i_copy_rstate (scm_t_i_rstate
*state
)
145 scm_t_rstate
*new_state
= scm_malloc (scm_the_rng
.rstate_size
);
147 scm_memory_error ("rstate");
148 return memcpy (new_state
, state
, scm_the_rng
.rstate_size
);
153 * Random number library functions
157 scm_c_make_rstate (const char *seed
, int n
)
159 scm_t_rstate
*state
= scm_malloc (scm_the_rng
.rstate_size
);
161 scm_memory_error ("rstate");
162 state
->reserved0
= 0;
163 scm_the_rng
.init_rstate (state
, seed
, n
);
169 scm_c_default_rstate ()
170 #define FUNC_NAME "scm_c_default_rstate"
172 SCM state
= SCM_VARIABLE_REF (scm_var_random_state
);
173 if (!SCM_RSTATEP (state
))
174 SCM_MISC_ERROR ("*random-state* contains bogus random state", SCM_EOL
);
175 return SCM_RSTATE (state
);
181 scm_c_uniform01 (scm_t_rstate
*state
)
183 double x
= (double) scm_the_rng
.random_bits (state
) / (double) 0xffffffffUL
;
184 return ((x
+ (double) scm_the_rng
.random_bits (state
))
185 / (double) 0xffffffffUL
);
189 scm_c_normal01 (scm_t_rstate
*state
)
191 if (state
->reserved0
)
193 state
->reserved0
= 0;
194 return state
->reserved1
;
200 r
= sqrt (-2.0 * log (scm_c_uniform01 (state
)));
201 a
= 2.0 * M_PI
* scm_c_uniform01 (state
);
204 state
->reserved1
= r
* cos (a
);
205 state
->reserved0
= 1;
212 scm_c_exp1 (scm_t_rstate
*state
)
214 return - log (scm_c_uniform01 (state
));
217 unsigned char scm_masktab
[256];
220 scm_c_random (scm_t_rstate
*state
, unsigned long m
)
222 unsigned int r
, mask
;
226 ? scm_masktab
[m
>> 8] << 8 | 0xff
228 ? scm_masktab
[m
>> 16] << 16 | 0xffff
229 : scm_masktab
[m
>> 24] << 24 | 0xffffff)));
230 while ((r
= scm_the_rng
.random_bits (state
) & mask
) >= m
);
235 SCM scm_c_random_bignum (scm_t_rstate *state, SCM m)
237 Takes a random state (source of random bits) and a bignum m.
238 Returns a bignum b, 0 <= b < m.
240 It does this by allocating a bignum b with as many base 65536 digits
241 as m, filling b with random bits (in 32 bit chunks) up to the most
242 significant 1 in m, and, finally checking if the resultant b is too
243 large (>= m). If too large, we simply repeat the process again. (It
244 is important to throw away all generated random bits if b >= m,
245 otherwise we'll end up with a distorted distribution.)
250 scm_c_random_bignum (scm_t_rstate
*state
, SCM m
)
252 SCM result
= scm_i_mkbig ();
253 const size_t m_bits
= mpz_sizeinbase (SCM_I_BIG_MPZ (m
), 2);
254 /* how many bits would only partially fill the last unsigned long? */
255 const size_t end_bits
= m_bits
% (sizeof (unsigned long) * SCM_CHAR_BIT
);
256 unsigned long *random_chunks
= NULL
;
257 const unsigned long num_full_chunks
=
258 m_bits
/ (sizeof (unsigned long) * SCM_CHAR_BIT
);
259 const unsigned long num_chunks
= num_full_chunks
+ ((end_bits
) ? 1 : 0);
261 /* we know the result will be this big */
262 mpz_realloc2 (SCM_I_BIG_MPZ (result
), m_bits
);
265 (unsigned long *) scm_gc_calloc (num_chunks
* sizeof (unsigned long),
266 "random bignum chunks");
270 unsigned long *current_chunk
= random_chunks
+ (num_chunks
- 1);
271 unsigned long chunks_left
= num_chunks
;
273 mpz_set_ui (SCM_I_BIG_MPZ (result
), 0);
277 /* generate a mask with ones in the end_bits position, i.e. if
278 end_bits is 3, then we'd have a mask of ...0000000111 */
279 const unsigned long rndbits
= scm_the_rng
.random_bits (state
);
280 int rshift
= (sizeof (unsigned long) * SCM_CHAR_BIT
) - end_bits
;
281 unsigned long mask
= ((unsigned long) ULONG_MAX
) >> rshift
;
282 unsigned long highest_bits
= rndbits
& mask
;
283 *current_chunk
-- = highest_bits
;
289 /* now fill in the remaining unsigned long sized chunks */
290 *current_chunk
-- = scm_the_rng
.random_bits (state
);
293 mpz_import (SCM_I_BIG_MPZ (result
),
296 sizeof (unsigned long),
300 /* if result >= m, regenerate it (it is important to regenerate
301 all bits in order not to get a distorted distribution) */
302 } while (mpz_cmp (SCM_I_BIG_MPZ (result
), SCM_I_BIG_MPZ (m
)) >= 0);
303 scm_gc_free (random_chunks
,
304 num_chunks
* sizeof (unsigned long),
305 "random bignum chunks");
306 return scm_i_normbig (result
);
310 * Scheme level representation of random states.
313 scm_t_bits scm_tc16_rstate
;
316 make_rstate (scm_t_rstate
*state
)
318 SCM_RETURN_NEWSMOB (scm_tc16_rstate
, state
);
322 rstate_free (SCM rstate
)
324 free (SCM_RSTATE (rstate
));
329 * Scheme level interface.
332 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")));
334 SCM_DEFINE (scm_random
, "random", 1, 1, 0,
336 "Return a number in [0, N).\n"
338 "Accepts a positive integer or real n and returns a\n"
339 "number of the same type between zero (inclusive) and\n"
340 "N (exclusive). The values returned have a uniform\n"
343 "The optional argument @var{state} must be of the type produced\n"
344 "by @code{seed->random-state}. It defaults to the value of the\n"
345 "variable @var{*random-state*}. This object is used to maintain\n"
346 "the state of the pseudo-random-number generator and is altered\n"
347 "as a side effect of the random operation.")
348 #define FUNC_NAME s_scm_random
350 if (SCM_UNBNDP (state
))
351 state
= SCM_VARIABLE_REF (scm_var_random_state
);
352 SCM_VALIDATE_RSTATE (2, state
);
355 unsigned long m
= SCM_I_INUM (n
);
356 SCM_ASSERT_RANGE (1, n
, m
> 0);
357 return scm_from_ulong (scm_c_random (SCM_RSTATE (state
), m
));
359 SCM_VALIDATE_NIM (1, n
);
361 return scm_from_double (SCM_REAL_VALUE (n
)
362 * scm_c_uniform01 (SCM_RSTATE (state
)));
365 SCM_WRONG_TYPE_ARG (1, n
);
366 return scm_c_random_bignum (SCM_RSTATE (state
), n
);
370 SCM_DEFINE (scm_copy_random_state
, "copy-random-state", 0, 1, 0,
372 "Return a copy of the random state @var{state}.")
373 #define FUNC_NAME s_scm_copy_random_state
375 if (SCM_UNBNDP (state
))
376 state
= SCM_VARIABLE_REF (scm_var_random_state
);
377 SCM_VALIDATE_RSTATE (1, state
);
378 return make_rstate (scm_the_rng
.copy_rstate (SCM_RSTATE (state
)));
382 SCM_DEFINE (scm_seed_to_random_state
, "seed->random-state", 1, 0, 0,
384 "Return a new random state using @var{seed}.")
385 #define FUNC_NAME s_scm_seed_to_random_state
388 if (SCM_NUMBERP (seed
))
389 seed
= scm_number_to_string (seed
, SCM_UNDEFINED
);
390 SCM_VALIDATE_STRING (1, seed
);
391 res
= make_rstate (scm_c_make_rstate (scm_i_string_chars (seed
),
392 scm_i_string_length (seed
)));
393 scm_remember_upto_here_1 (seed
);
399 SCM_DEFINE (scm_random_uniform
, "random:uniform", 0, 1, 0,
401 "Return a uniformly distributed inexact real random number in\n"
403 #define FUNC_NAME s_scm_random_uniform
405 if (SCM_UNBNDP (state
))
406 state
= SCM_VARIABLE_REF (scm_var_random_state
);
407 SCM_VALIDATE_RSTATE (1, state
);
408 return scm_from_double (scm_c_uniform01 (SCM_RSTATE (state
)));
412 SCM_DEFINE (scm_random_normal
, "random:normal", 0, 1, 0,
414 "Return an inexact real in a normal distribution. The\n"
415 "distribution used has mean 0 and standard deviation 1. For a\n"
416 "normal distribution with mean m and standard deviation d use\n"
417 "@code{(+ m (* d (random:normal)))}.")
418 #define FUNC_NAME s_scm_random_normal
420 if (SCM_UNBNDP (state
))
421 state
= SCM_VARIABLE_REF (scm_var_random_state
);
422 SCM_VALIDATE_RSTATE (1, state
);
423 return scm_from_double (scm_c_normal01 (SCM_RSTATE (state
)));
428 vector_scale_x (SCM v
, double c
)
431 if (scm_is_simple_vector (v
))
433 n
= SCM_SIMPLE_VECTOR_LENGTH (v
);
435 SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v
, n
)) *= c
;
439 /* must be a f64vector. */
440 scm_t_array_handle handle
;
445 elts
= scm_f64vector_writable_elements (v
, &handle
, &len
, &inc
);
447 for (i
= 0; i
< len
; i
++, elts
+= inc
)
450 scm_array_handle_release (&handle
);
455 vector_sum_squares (SCM v
)
459 if (scm_is_simple_vector (v
))
461 n
= SCM_SIMPLE_VECTOR_LENGTH (v
);
464 x
= SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v
, n
));
470 /* must be a f64vector. */
471 scm_t_array_handle handle
;
476 elts
= scm_f64vector_elements (v
, &handle
, &len
, &inc
);
478 for (i
= 0; i
< len
; i
++, elts
+= inc
)
484 scm_array_handle_release (&handle
);
489 /* For the uniform distribution on the solid sphere, note that in
490 * this distribution the length r of the vector has cumulative
491 * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
492 * generated as r=u^(1/n).
494 SCM_DEFINE (scm_random_solid_sphere_x
, "random:solid-sphere!", 1, 1, 0,
496 "Fills @var{vect} with inexact real random numbers the sum of\n"
497 "whose squares is less than 1.0. Thinking of @var{vect} as\n"
498 "coordinates in space of dimension @var{n} @math{=}\n"
499 "@code{(vector-length @var{vect})}, the coordinates are\n"
500 "uniformly distributed within the unit @var{n}-sphere.")
501 #define FUNC_NAME s_scm_random_solid_sphere_x
503 if (SCM_UNBNDP (state
))
504 state
= SCM_VARIABLE_REF (scm_var_random_state
);
505 SCM_VALIDATE_RSTATE (2, state
);
506 scm_random_normal_vector_x (v
, state
);
508 pow (scm_c_uniform01 (SCM_RSTATE (state
)),
509 1.0 / scm_c_generalized_vector_length (v
))
510 / sqrt (vector_sum_squares (v
)));
511 return SCM_UNSPECIFIED
;
515 SCM_DEFINE (scm_random_hollow_sphere_x
, "random:hollow-sphere!", 1, 1, 0,
517 "Fills vect with inexact real random numbers\n"
518 "the sum of whose squares is equal to 1.0.\n"
519 "Thinking of vect as coordinates in space of\n"
520 "dimension n = (vector-length vect), the coordinates\n"
521 "are uniformly distributed over the surface of the\n"
523 #define FUNC_NAME s_scm_random_hollow_sphere_x
525 if (SCM_UNBNDP (state
))
526 state
= SCM_VARIABLE_REF (scm_var_random_state
);
527 SCM_VALIDATE_RSTATE (2, state
);
528 scm_random_normal_vector_x (v
, state
);
529 vector_scale_x (v
, 1 / sqrt (vector_sum_squares (v
)));
530 return SCM_UNSPECIFIED
;
535 SCM_DEFINE (scm_random_normal_vector_x
, "random:normal-vector!", 1, 1, 0,
537 "Fills vect with inexact real random numbers that are\n"
538 "independent and standard normally distributed\n"
539 "(i.e., with mean 0 and variance 1).")
540 #define FUNC_NAME s_scm_random_normal_vector_x
543 scm_t_array_handle handle
;
544 scm_t_array_dim
*dim
;
546 if (SCM_UNBNDP (state
))
547 state
= SCM_VARIABLE_REF (scm_var_random_state
);
548 SCM_VALIDATE_RSTATE (2, state
);
550 scm_generalized_vector_get_handle (v
, &handle
);
551 dim
= scm_array_handle_dims (&handle
);
553 if (scm_is_vector (v
))
555 SCM
*elts
= scm_array_handle_writable_elements (&handle
);
556 for (i
= dim
->lbnd
; i
<= dim
->ubnd
; i
++, elts
+= dim
->inc
)
557 *elts
= scm_from_double (scm_c_normal01 (SCM_RSTATE (state
)));
561 /* must be a f64vector. */
562 double *elts
= scm_array_handle_f64_writable_elements (&handle
);
563 for (i
= dim
->lbnd
; i
<= dim
->ubnd
; i
++, elts
+= dim
->inc
)
564 *elts
= scm_c_normal01 (SCM_RSTATE (state
));
567 scm_array_handle_release (&handle
);
569 return SCM_UNSPECIFIED
;
573 SCM_DEFINE (scm_random_exp
, "random:exp", 0, 1, 0,
575 "Return an inexact real in an exponential distribution with mean\n"
576 "1. For an exponential distribution with mean u use (* u\n"
578 #define FUNC_NAME s_scm_random_exp
580 if (SCM_UNBNDP (state
))
581 state
= SCM_VARIABLE_REF (scm_var_random_state
);
582 SCM_VALIDATE_RSTATE (1, state
);
583 return scm_from_double (scm_c_exp1 (SCM_RSTATE (state
)));
591 /* plug in default RNG */
594 sizeof (scm_t_i_rstate
),
595 (unsigned long (*)()) scm_i_uniform32
,
596 (void (*)()) scm_i_init_rstate
,
597 (scm_t_rstate
*(*)()) scm_i_copy_rstate
601 scm_tc16_rstate
= scm_make_smob_type ("random-state", 0);
602 scm_set_smob_free (scm_tc16_rstate
, rstate_free
);
604 for (m
= 1; m
<= 0x100; m
<<= 1)
605 for (i
= m
>> 1; i
< m
; ++i
)
606 scm_masktab
[i
] = m
- 1;
608 #include "libguile/random.x"
610 scm_add_feature ("random");