random.c 17 KB

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