random.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /* Copyright (C) 1999,2000,2001, 2003, 2005, 2006 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.
  6. *
  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.
  11. *
  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
  15. */
  16. /* Author: Mikael Djurfeldt <djurfeldt@nada.kth.se> */
  17. #ifdef HAVE_CONFIG_H
  18. # include <config.h>
  19. #endif
  20. #include "libguile/_scm.h"
  21. #include <gmp.h>
  22. #include <stdio.h>
  23. #include <math.h>
  24. #include <string.h>
  25. #include "libguile/smob.h"
  26. #include "libguile/numbers.h"
  27. #include "libguile/feature.h"
  28. #include "libguile/strings.h"
  29. #include "libguile/unif.h"
  30. #include "libguile/srfi-4.h"
  31. #include "libguile/vectors.h"
  32. #include "libguile/validate.h"
  33. #include "libguile/random.h"
  34. /*
  35. * A plugin interface for RNGs
  36. *
  37. * Using this interface, it is possible for the application to tell
  38. * libguile to use a different RNG. This is desirable if it is
  39. * necessary to use the same RNG everywhere in the application in
  40. * order to prevent interference, if the application uses RNG
  41. * hardware, or if the application has special demands on the RNG.
  42. *
  43. * Look in random.h and how the default generator is "plugged in" in
  44. * scm_init_random().
  45. */
  46. scm_t_rng scm_the_rng;
  47. /*
  48. * The prepackaged RNG
  49. *
  50. * This is the MWC (Multiply With Carry) random number generator
  51. * described by George Marsaglia at the Department of Statistics and
  52. * Supercomputer Computations Research Institute, The Florida State
  53. * University (http://stat.fsu.edu/~geo).
  54. *
  55. * It uses 64 bits, has a period of 4578426017172946943 (4.6e18), and
  56. * passes all tests in the DIEHARD test suite
  57. * (http://stat.fsu.edu/~geo/diehard.html)
  58. */
  59. #define A 2131995753UL
  60. #ifndef M_PI
  61. #define M_PI 3.14159265359
  62. #endif
  63. #if SCM_HAVE_T_UINT64
  64. unsigned long
  65. scm_i_uniform32 (scm_t_i_rstate *state)
  66. {
  67. scm_t_uint64 x = (scm_t_uint64) A * state->w + state->c;
  68. scm_t_uint32 w = x & 0xffffffffUL;
  69. state->w = w;
  70. state->c = x >> 32L;
  71. return w;
  72. }
  73. #else
  74. /* ww This is a portable version of the same RNG without 64 bit
  75. * * aa arithmetic.
  76. * ----
  77. * xx It is only intended to provide identical behaviour on
  78. * xx platforms without 8 byte longs or long longs until
  79. * xx someone has implemented the routine in assembler code.
  80. * xxcc
  81. * ----
  82. * ccww
  83. */
  84. #define L(x) ((x) & 0xffff)
  85. #define H(x) ((x) >> 16)
  86. unsigned long
  87. scm_i_uniform32 (scm_t_i_rstate *state)
  88. {
  89. scm_t_uint32 x1 = L (A) * L (state->w);
  90. scm_t_uint32 x2 = L (A) * H (state->w);
  91. scm_t_uint32 x3 = H (A) * L (state->w);
  92. scm_t_uint32 w = L (x1) + L (state->c);
  93. scm_t_uint32 m = H (x1) + L (x2) + L (x3) + H (state->c) + H (w);
  94. scm_t_uint32 x4 = H (A) * H (state->w);
  95. state->w = w = (L (m) << 16) + L (w);
  96. state->c = H (x2) + H (x3) + x4 + H (m);
  97. return w;
  98. }
  99. #endif
  100. void
  101. scm_i_init_rstate (scm_t_i_rstate *state, const char *seed, int n)
  102. {
  103. scm_t_uint32 w = 0L;
  104. scm_t_uint32 c = 0L;
  105. int i, m;
  106. for (i = 0; i < n; ++i)
  107. {
  108. m = i % 8;
  109. if (m < 4)
  110. w += seed[i] << (8 * m);
  111. else
  112. c += seed[i] << (8 * (m - 4));
  113. }
  114. if ((w == 0 && c == 0) || (w == -1 && c == A - 1))
  115. ++c;
  116. state->w = w;
  117. state->c = c;
  118. }
  119. scm_t_i_rstate *
  120. scm_i_copy_rstate (scm_t_i_rstate *state)
  121. {
  122. scm_t_rstate *new_state = scm_malloc (scm_the_rng.rstate_size);
  123. return memcpy (new_state, state, scm_the_rng.rstate_size);
  124. }
  125. /*
  126. * Random number library functions
  127. */
  128. scm_t_rstate *
  129. scm_c_make_rstate (const char *seed, int n)
  130. {
  131. scm_t_rstate *state = scm_malloc (scm_the_rng.rstate_size);
  132. state->reserved0 = 0;
  133. scm_the_rng.init_rstate (state, seed, n);
  134. return state;
  135. }
  136. scm_t_rstate *
  137. scm_c_default_rstate ()
  138. #define FUNC_NAME "scm_c_default_rstate"
  139. {
  140. SCM state = SCM_VARIABLE_REF (scm_var_random_state);
  141. if (!SCM_RSTATEP (state))
  142. SCM_MISC_ERROR ("*random-state* contains bogus random state", SCM_EOL);
  143. return SCM_RSTATE (state);
  144. }
  145. #undef FUNC_NAME
  146. inline double
  147. scm_c_uniform01 (scm_t_rstate *state)
  148. {
  149. double x = (double) scm_the_rng.random_bits (state) / (double) 0xffffffffUL;
  150. return ((x + (double) scm_the_rng.random_bits (state))
  151. / (double) 0xffffffffUL);
  152. }
  153. double
  154. scm_c_normal01 (scm_t_rstate *state)
  155. {
  156. if (state->reserved0)
  157. {
  158. state->reserved0 = 0;
  159. return state->reserved1;
  160. }
  161. else
  162. {
  163. double r, a, n;
  164. r = sqrt (-2.0 * log (scm_c_uniform01 (state)));
  165. a = 2.0 * M_PI * scm_c_uniform01 (state);
  166. n = r * sin (a);
  167. state->reserved1 = r * cos (a);
  168. state->reserved0 = 1;
  169. return n;
  170. }
  171. }
  172. double
  173. scm_c_exp1 (scm_t_rstate *state)
  174. {
  175. return - log (scm_c_uniform01 (state));
  176. }
  177. unsigned char scm_masktab[256];
  178. unsigned long
  179. scm_c_random (scm_t_rstate *state, unsigned long m)
  180. {
  181. unsigned int r, mask;
  182. mask = (m < 0x100
  183. ? scm_masktab[m]
  184. : (m < 0x10000
  185. ? scm_masktab[m >> 8] << 8 | 0xff
  186. : (m < 0x1000000
  187. ? scm_masktab[m >> 16] << 16 | 0xffff
  188. : scm_masktab[m >> 24] << 24 | 0xffffff)));
  189. while ((r = scm_the_rng.random_bits (state) & mask) >= m);
  190. return r;
  191. }
  192. /*
  193. SCM scm_c_random_bignum (scm_t_rstate *state, SCM m)
  194. Takes a random state (source of random bits) and a bignum m.
  195. Returns a bignum b, 0 <= b < m.
  196. It does this by allocating a bignum b with as many base 65536 digits
  197. as m, filling b with random bits (in 32 bit chunks) up to the most
  198. significant 1 in m, and, finally checking if the resultant b is too
  199. large (>= m). If too large, we simply repeat the process again. (It
  200. is important to throw away all generated random bits if b >= m,
  201. otherwise we'll end up with a distorted distribution.)
  202. */
  203. SCM
  204. scm_c_random_bignum (scm_t_rstate *state, SCM m)
  205. {
  206. SCM result = scm_i_mkbig ();
  207. const size_t m_bits = mpz_sizeinbase (SCM_I_BIG_MPZ (m), 2);
  208. /* how many bits would only partially fill the last unsigned long? */
  209. const size_t end_bits = m_bits % (sizeof (unsigned long) * SCM_CHAR_BIT);
  210. unsigned long *random_chunks = NULL;
  211. const unsigned long num_full_chunks =
  212. m_bits / (sizeof (unsigned long) * SCM_CHAR_BIT);
  213. const unsigned long num_chunks = num_full_chunks + ((end_bits) ? 1 : 0);
  214. /* we know the result will be this big */
  215. mpz_realloc2 (SCM_I_BIG_MPZ (result), m_bits);
  216. random_chunks =
  217. (unsigned long *) scm_gc_calloc (num_chunks * sizeof (unsigned long),
  218. "random bignum chunks");
  219. do
  220. {
  221. unsigned long *current_chunk = random_chunks + (num_chunks - 1);
  222. unsigned long chunks_left = num_chunks;
  223. mpz_set_ui (SCM_I_BIG_MPZ (result), 0);
  224. if (end_bits)
  225. {
  226. /* generate a mask with ones in the end_bits position, i.e. if
  227. end_bits is 3, then we'd have a mask of ...0000000111 */
  228. const unsigned long rndbits = scm_the_rng.random_bits (state);
  229. int rshift = (sizeof (unsigned long) * SCM_CHAR_BIT) - end_bits;
  230. unsigned long mask = ((unsigned long) ULONG_MAX) >> rshift;
  231. unsigned long highest_bits = rndbits & mask;
  232. *current_chunk-- = highest_bits;
  233. chunks_left--;
  234. }
  235. while (chunks_left)
  236. {
  237. /* now fill in the remaining unsigned long sized chunks */
  238. *current_chunk-- = scm_the_rng.random_bits (state);
  239. chunks_left--;
  240. }
  241. mpz_import (SCM_I_BIG_MPZ (result),
  242. num_chunks,
  243. -1,
  244. sizeof (unsigned long),
  245. 0,
  246. 0,
  247. random_chunks);
  248. /* if result >= m, regenerate it (it is important to regenerate
  249. all bits in order not to get a distorted distribution) */
  250. } while (mpz_cmp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (m)) >= 0);
  251. scm_gc_free (random_chunks,
  252. num_chunks * sizeof (unsigned long),
  253. "random bignum chunks");
  254. return scm_i_normbig (result);
  255. }
  256. /*
  257. * Scheme level representation of random states.
  258. */
  259. scm_t_bits scm_tc16_rstate;
  260. static SCM
  261. make_rstate (scm_t_rstate *state)
  262. {
  263. SCM_RETURN_NEWSMOB (scm_tc16_rstate, state);
  264. }
  265. static size_t
  266. rstate_free (SCM rstate)
  267. {
  268. free (SCM_RSTATE (rstate));
  269. return 0;
  270. }
  271. /*
  272. * Scheme level interface.
  273. */
  274. 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")));
  275. SCM_DEFINE (scm_random, "random", 1, 1, 0,
  276. (SCM n, SCM state),
  277. "Return a number in [0, N).\n"
  278. "\n"
  279. "Accepts a positive integer or real n and returns a\n"
  280. "number of the same type between zero (inclusive) and\n"
  281. "N (exclusive). The values returned have a uniform\n"
  282. "distribution.\n"
  283. "\n"
  284. "The optional argument @var{state} must be of the type produced\n"
  285. "by @code{seed->random-state}. It defaults to the value of the\n"
  286. "variable @var{*random-state*}. This object is used to maintain\n"
  287. "the state of the pseudo-random-number generator and is altered\n"
  288. "as a side effect of the random operation.")
  289. #define FUNC_NAME s_scm_random
  290. {
  291. if (SCM_UNBNDP (state))
  292. state = SCM_VARIABLE_REF (scm_var_random_state);
  293. SCM_VALIDATE_RSTATE (2, state);
  294. if (SCM_I_INUMP (n))
  295. {
  296. unsigned long m = SCM_I_INUM (n);
  297. SCM_ASSERT_RANGE (1, n, m > 0);
  298. return scm_from_ulong (scm_c_random (SCM_RSTATE (state), m));
  299. }
  300. SCM_VALIDATE_NIM (1, n);
  301. if (SCM_REALP (n))
  302. return scm_from_double (SCM_REAL_VALUE (n)
  303. * scm_c_uniform01 (SCM_RSTATE (state)));
  304. if (!SCM_BIGP (n))
  305. SCM_WRONG_TYPE_ARG (1, n);
  306. return scm_c_random_bignum (SCM_RSTATE (state), n);
  307. }
  308. #undef FUNC_NAME
  309. SCM_DEFINE (scm_copy_random_state, "copy-random-state", 0, 1, 0,
  310. (SCM state),
  311. "Return a copy of the random state @var{state}.")
  312. #define FUNC_NAME s_scm_copy_random_state
  313. {
  314. if (SCM_UNBNDP (state))
  315. state = SCM_VARIABLE_REF (scm_var_random_state);
  316. SCM_VALIDATE_RSTATE (1, state);
  317. return make_rstate (scm_the_rng.copy_rstate (SCM_RSTATE (state)));
  318. }
  319. #undef FUNC_NAME
  320. SCM_DEFINE (scm_seed_to_random_state, "seed->random-state", 1, 0, 0,
  321. (SCM seed),
  322. "Return a new random state using @var{seed}.")
  323. #define FUNC_NAME s_scm_seed_to_random_state
  324. {
  325. SCM res;
  326. if (SCM_NUMBERP (seed))
  327. seed = scm_number_to_string (seed, SCM_UNDEFINED);
  328. SCM_VALIDATE_STRING (1, seed);
  329. res = make_rstate (scm_c_make_rstate (scm_i_string_chars (seed),
  330. scm_i_string_length (seed)));
  331. scm_remember_upto_here_1 (seed);
  332. return res;
  333. }
  334. #undef FUNC_NAME
  335. SCM_DEFINE (scm_random_uniform, "random:uniform", 0, 1, 0,
  336. (SCM state),
  337. "Return a uniformly distributed inexact real random number in\n"
  338. "[0,1).")
  339. #define FUNC_NAME s_scm_random_uniform
  340. {
  341. if (SCM_UNBNDP (state))
  342. state = SCM_VARIABLE_REF (scm_var_random_state);
  343. SCM_VALIDATE_RSTATE (1, state);
  344. return scm_from_double (scm_c_uniform01 (SCM_RSTATE (state)));
  345. }
  346. #undef FUNC_NAME
  347. SCM_DEFINE (scm_random_normal, "random:normal", 0, 1, 0,
  348. (SCM state),
  349. "Return an inexact real in a normal distribution. The\n"
  350. "distribution used has mean 0 and standard deviation 1. For a\n"
  351. "normal distribution with mean m and standard deviation d use\n"
  352. "@code{(+ m (* d (random:normal)))}.")
  353. #define FUNC_NAME s_scm_random_normal
  354. {
  355. if (SCM_UNBNDP (state))
  356. state = SCM_VARIABLE_REF (scm_var_random_state);
  357. SCM_VALIDATE_RSTATE (1, state);
  358. return scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
  359. }
  360. #undef FUNC_NAME
  361. static void
  362. vector_scale_x (SCM v, double c)
  363. {
  364. size_t n;
  365. if (scm_is_simple_vector (v))
  366. {
  367. n = SCM_SIMPLE_VECTOR_LENGTH (v);
  368. while (n-- > 0)
  369. SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v, n)) *= c;
  370. }
  371. else
  372. {
  373. /* must be a f64vector. */
  374. scm_t_array_handle handle;
  375. size_t i, len;
  376. ssize_t inc;
  377. double *elts;
  378. elts = scm_f64vector_writable_elements (v, &handle, &len, &inc);
  379. for (i = 0; i < len; i++, elts += inc)
  380. *elts *= c;
  381. scm_array_handle_release (&handle);
  382. }
  383. }
  384. static double
  385. vector_sum_squares (SCM v)
  386. {
  387. double x, sum = 0.0;
  388. size_t n;
  389. if (scm_is_simple_vector (v))
  390. {
  391. n = SCM_SIMPLE_VECTOR_LENGTH (v);
  392. while (n-- > 0)
  393. {
  394. x = SCM_REAL_VALUE (SCM_SIMPLE_VECTOR_REF (v, n));
  395. sum += x * x;
  396. }
  397. }
  398. else
  399. {
  400. /* must be a f64vector. */
  401. scm_t_array_handle handle;
  402. size_t i, len;
  403. ssize_t inc;
  404. const double *elts;
  405. elts = scm_f64vector_elements (v, &handle, &len, &inc);
  406. for (i = 0; i < len; i++, elts += inc)
  407. {
  408. x = *elts;
  409. sum += x * x;
  410. }
  411. scm_array_handle_release (&handle);
  412. }
  413. return sum;
  414. }
  415. /* For the uniform distribution on the solid sphere, note that in
  416. * this distribution the length r of the vector has cumulative
  417. * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
  418. * generated as r=u^(1/n).
  419. */
  420. SCM_DEFINE (scm_random_solid_sphere_x, "random:solid-sphere!", 1, 1, 0,
  421. (SCM v, SCM state),
  422. "Fills @var{vect} with inexact real random numbers the sum of\n"
  423. "whose squares is less than 1.0. Thinking of @var{vect} as\n"
  424. "coordinates in space of dimension @var{n} @math{=}\n"
  425. "@code{(vector-length @var{vect})}, the coordinates are\n"
  426. "uniformly distributed within the unit @var{n}-sphere.")
  427. #define FUNC_NAME s_scm_random_solid_sphere_x
  428. {
  429. if (SCM_UNBNDP (state))
  430. state = SCM_VARIABLE_REF (scm_var_random_state);
  431. SCM_VALIDATE_RSTATE (2, state);
  432. scm_random_normal_vector_x (v, state);
  433. vector_scale_x (v,
  434. pow (scm_c_uniform01 (SCM_RSTATE (state)),
  435. 1.0 / scm_c_generalized_vector_length (v))
  436. / sqrt (vector_sum_squares (v)));
  437. return SCM_UNSPECIFIED;
  438. }
  439. #undef FUNC_NAME
  440. SCM_DEFINE (scm_random_hollow_sphere_x, "random:hollow-sphere!", 1, 1, 0,
  441. (SCM v, SCM state),
  442. "Fills vect with inexact real random numbers\n"
  443. "the sum of whose squares is equal to 1.0.\n"
  444. "Thinking of vect as coordinates in space of\n"
  445. "dimension n = (vector-length vect), the coordinates\n"
  446. "are uniformly distributed over the surface of the\n"
  447. "unit n-sphere.")
  448. #define FUNC_NAME s_scm_random_hollow_sphere_x
  449. {
  450. if (SCM_UNBNDP (state))
  451. state = SCM_VARIABLE_REF (scm_var_random_state);
  452. SCM_VALIDATE_RSTATE (2, state);
  453. scm_random_normal_vector_x (v, state);
  454. vector_scale_x (v, 1 / sqrt (vector_sum_squares (v)));
  455. return SCM_UNSPECIFIED;
  456. }
  457. #undef FUNC_NAME
  458. SCM_DEFINE (scm_random_normal_vector_x, "random:normal-vector!", 1, 1, 0,
  459. (SCM v, SCM state),
  460. "Fills vect with inexact real random numbers that are\n"
  461. "independent and standard normally distributed\n"
  462. "(i.e., with mean 0 and variance 1).")
  463. #define FUNC_NAME s_scm_random_normal_vector_x
  464. {
  465. long i;
  466. scm_t_array_handle handle;
  467. scm_t_array_dim *dim;
  468. if (SCM_UNBNDP (state))
  469. state = SCM_VARIABLE_REF (scm_var_random_state);
  470. SCM_VALIDATE_RSTATE (2, state);
  471. scm_generalized_vector_get_handle (v, &handle);
  472. dim = scm_array_handle_dims (&handle);
  473. if (scm_is_vector (v))
  474. {
  475. SCM *elts = scm_array_handle_writable_elements (&handle);
  476. for (i = dim->lbnd; i <= dim->ubnd; i++, elts += dim->inc)
  477. *elts = scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
  478. }
  479. else
  480. {
  481. /* must be a f64vector. */
  482. double *elts = scm_array_handle_f64_writable_elements (&handle);
  483. for (i = dim->lbnd; i <= dim->ubnd; i++, elts += dim->inc)
  484. *elts = scm_c_normal01 (SCM_RSTATE (state));
  485. }
  486. scm_array_handle_release (&handle);
  487. return SCM_UNSPECIFIED;
  488. }
  489. #undef FUNC_NAME
  490. SCM_DEFINE (scm_random_exp, "random:exp", 0, 1, 0,
  491. (SCM state),
  492. "Return an inexact real in an exponential distribution with mean\n"
  493. "1. For an exponential distribution with mean u use (* u\n"
  494. "(random:exp)).")
  495. #define FUNC_NAME s_scm_random_exp
  496. {
  497. if (SCM_UNBNDP (state))
  498. state = SCM_VARIABLE_REF (scm_var_random_state);
  499. SCM_VALIDATE_RSTATE (1, state);
  500. return scm_from_double (scm_c_exp1 (SCM_RSTATE (state)));
  501. }
  502. #undef FUNC_NAME
  503. void
  504. scm_init_random ()
  505. {
  506. int i, m;
  507. /* plug in default RNG */
  508. scm_t_rng rng =
  509. {
  510. sizeof (scm_t_i_rstate),
  511. (unsigned long (*)()) scm_i_uniform32,
  512. (void (*)()) scm_i_init_rstate,
  513. (scm_t_rstate *(*)()) scm_i_copy_rstate
  514. };
  515. scm_the_rng = rng;
  516. scm_tc16_rstate = scm_make_smob_type ("random-state", 0);
  517. scm_set_smob_free (scm_tc16_rstate, rstate_free);
  518. for (m = 1; m <= 0x100; m <<= 1)
  519. for (i = m >> 1; i < m; ++i)
  520. scm_masktab[i] = m - 1;
  521. #include "libguile/random.x"
  522. scm_add_feature ("random");
  523. }
  524. /*
  525. Local Variables:
  526. c-file-style: "gnu"
  527. End:
  528. */