random.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /* Copyright (C) 1999, 2000, 2002 Free Software Foundation, Inc.
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2, or (at your option)
  5. * any later version.
  6. *
  7. * This program 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
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this software; see the file COPYING. If not, write to
  14. * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  15. * Boston, MA 02111-1307 USA
  16. *
  17. * As a special exception, the Free Software Foundation gives permission
  18. * for additional uses of the text contained in its release of GUILE.
  19. *
  20. * The exception is that, if you link the GUILE library with other files
  21. * to produce an executable, this does not by itself cause the
  22. * resulting executable to be covered by the GNU General Public License.
  23. * Your use of that executable is in no way restricted on account of
  24. * linking the GUILE library code into it.
  25. *
  26. * This exception does not however invalidate any other reasons why
  27. * the executable file might be covered by the GNU General Public License.
  28. *
  29. * This exception applies only to the code released by the
  30. * Free Software Foundation under the name GUILE. If you copy
  31. * code from other Free Software Foundation releases into a copy of
  32. * GUILE, as the General Public License permits, the exception does
  33. * not apply to the code that you add in this way. To avoid misleading
  34. * anyone as to the status of such modified files, you must delete
  35. * this exception notice from them.
  36. *
  37. * If you write modifications of your own for GUILE, it is your choice
  38. * whether to permit this exception to apply to your modifications.
  39. * If you do not wish that, delete this exception notice. */
  40. /* Author: Mikael Djurfeldt <djurfeldt@nada.kth.se> */
  41. #include "libguile/_scm.h"
  42. #include <stdio.h>
  43. #include <math.h>
  44. #include <string.h>
  45. #include "libguile/smob.h"
  46. #include "libguile/numbers.h"
  47. #include "libguile/feature.h"
  48. #include "libguile/strings.h"
  49. #include "libguile/vectors.h"
  50. #include "libguile/validate.h"
  51. #include "libguile/random.h"
  52. /*
  53. * A plugin interface for RNGs
  54. *
  55. * Using this interface, it is possible for the application to tell
  56. * libguile to use a different RNG. This is desirable if it is
  57. * necessary to use the same RNG everywhere in the application in
  58. * order to prevent interference, if the application uses RNG
  59. * hardware, or if the application has special demands on the RNG.
  60. *
  61. * Look in random.h and how the default generator is "plugged in" in
  62. * scm_init_random().
  63. */
  64. scm_rng scm_the_rng;
  65. /*
  66. * The prepackaged RNG
  67. *
  68. * This is the MWC (Multiply With Carry) random number generator
  69. * described by George Marsaglia at the Department of Statistics and
  70. * Supercomputer Computations Research Institute, The Florida State
  71. * University (http://stat.fsu.edu/~geo).
  72. *
  73. * It uses 64 bits, has a period of 4578426017172946943 (4.6e18), and
  74. * passes all tests in the DIEHARD test suite
  75. * (http://stat.fsu.edu/~geo/diehard.html)
  76. */
  77. #define A 2131995753UL
  78. #if SIZEOF_LONG > 4
  79. #if SIZEOF_INT > 4
  80. #define LONG32 unsigned short
  81. #else
  82. #define LONG32 unsigned int
  83. #endif
  84. #define LONG64 unsigned long
  85. #else
  86. #define LONG32 unsigned long
  87. #define LONG64 unsigned long long
  88. #endif
  89. #if SIZEOF_LONG > 4 || defined (HAVE_LONG_LONGS)
  90. unsigned long
  91. scm_i_uniform32 (scm_i_rstate *state)
  92. {
  93. LONG64 x = (LONG64) A * state->w + state->c;
  94. LONG32 w = x & 0xffffffffUL;
  95. state->w = w;
  96. state->c = x >> 32L;
  97. return w;
  98. }
  99. #else
  100. /* ww This is a portable version of the same RNG without 64 bit
  101. * * aa arithmetic.
  102. * ----
  103. * xx It is only intended to provide identical behaviour on
  104. * xx platforms without 8 byte longs or long longs until
  105. * xx someone has implemented the routine in assembler code.
  106. * xxcc
  107. * ----
  108. * ccww
  109. */
  110. #define L(x) ((x) & 0xffff)
  111. #define H(x) ((x) >> 16)
  112. unsigned long
  113. scm_i_uniform32 (scm_i_rstate *state)
  114. {
  115. LONG32 x1 = L (A) * L (state->w);
  116. LONG32 x2 = L (A) * H (state->w);
  117. LONG32 x3 = H (A) * L (state->w);
  118. LONG32 w = L (x1) + L (state->c);
  119. LONG32 m = H (x1) + L (x2) + L (x3) + H (state->c) + H (w);
  120. LONG32 x4 = H (A) * H (state->w);
  121. state->w = w = (L (m) << 16) + L (w);
  122. state->c = H (x2) + H (x3) + x4 + H (m);
  123. return w;
  124. }
  125. #endif
  126. void
  127. scm_i_init_rstate (scm_i_rstate *state, char *seed, int n)
  128. {
  129. LONG32 w = 0L;
  130. LONG32 c = 0L;
  131. int i, m;
  132. for (i = 0; i < n; ++i)
  133. {
  134. m = i % 8;
  135. if (m < 4)
  136. w += seed[i] << (8 * m);
  137. else
  138. c += seed[i] << (8 * (m - 4));
  139. }
  140. if ((w == 0 && c == 0) || (w == 0xffffffffUL && c == A - 1))
  141. ++c;
  142. state->w = w;
  143. state->c = c;
  144. }
  145. scm_i_rstate *
  146. scm_i_copy_rstate (scm_i_rstate *state)
  147. {
  148. scm_rstate *new_state = malloc (scm_the_rng.rstate_size);
  149. if (new_state == 0)
  150. scm_wta (SCM_MAKINUM (scm_the_rng.rstate_size),
  151. (char *) SCM_NALLOC, "rstate");
  152. return memcpy (new_state, state, scm_the_rng.rstate_size);
  153. }
  154. /*
  155. * Random number library functions
  156. */
  157. scm_rstate *
  158. scm_c_make_rstate (char *seed, int n)
  159. {
  160. scm_rstate *state = malloc (scm_the_rng.rstate_size);
  161. if (state == 0)
  162. scm_wta (SCM_MAKINUM (scm_the_rng.rstate_size),
  163. (char *) SCM_NALLOC,
  164. "rstate");
  165. state->reserved0 = 0;
  166. scm_the_rng.init_rstate (state, seed, n);
  167. return state;
  168. }
  169. scm_rstate *
  170. scm_c_default_rstate ()
  171. {
  172. SCM state = SCM_CDR (scm_var_random_state);
  173. SCM_ASSERT (SCM_RSTATEP (state),
  174. state, "*random-state* contains bogus random state", 0);
  175. return SCM_RSTATE (state);
  176. }
  177. inline double
  178. scm_c_uniform01 (scm_rstate *state)
  179. {
  180. double x = (double) scm_the_rng.random_bits (state) / (double) 0xffffffffUL;
  181. return ((x + (double) scm_the_rng.random_bits (state))
  182. / (double) 0xffffffffUL);
  183. }
  184. double
  185. scm_c_normal01 (scm_rstate *state)
  186. {
  187. if (state->reserved0)
  188. {
  189. state->reserved0 = 0;
  190. return state->reserved1;
  191. }
  192. else
  193. {
  194. double r, a, n;
  195. r = sqrt (-2.0 * log (scm_c_uniform01 (state)));
  196. a = 2.0 * M_PI * scm_c_uniform01 (state);
  197. n = r * sin (a);
  198. state->reserved1 = r * cos (a);
  199. state->reserved0 = 1;
  200. return n;
  201. }
  202. }
  203. double
  204. scm_c_exp1 (scm_rstate *state)
  205. {
  206. return - log (scm_c_uniform01 (state));
  207. }
  208. unsigned char scm_masktab[256];
  209. unsigned long
  210. scm_c_random (scm_rstate *state, unsigned long m)
  211. {
  212. unsigned int r, mask;
  213. mask = (m < 0x100
  214. ? scm_masktab[m]
  215. : (m < 0x10000
  216. ? scm_masktab[m >> 8] << 8 | 0xff
  217. : (m < 0x1000000
  218. ? scm_masktab[m >> 16] << 16 | 0xffff
  219. : scm_masktab[m >> 24] << 24 | 0xffffff)));
  220. while ((r = scm_the_rng.random_bits (state) & mask) >= m);
  221. return r;
  222. }
  223. SCM
  224. scm_c_random_bignum (scm_rstate *state, SCM m)
  225. {
  226. SCM b;
  227. int i, nd;
  228. LONG32 *bits, mask, w;
  229. nd = SCM_NUMDIGS (m);
  230. /* calculate mask for most significant digit */
  231. #if SIZEOF_INT == 4
  232. /* 16 bit digits */
  233. if (nd & 1)
  234. {
  235. /* fix most significant 16 bits */
  236. unsigned short s = SCM_BDIGITS (m)[nd - 1];
  237. mask = s < 0x100 ? scm_masktab[s] : scm_masktab[s >> 8] << 8 | 0xff;
  238. }
  239. else
  240. #endif
  241. {
  242. /* fix most significant 32 bits */
  243. #if SIZEOF_INT == 4
  244. w = SCM_BDIGITS (m)[nd - 1] << 16 | SCM_BDIGITS (m)[nd - 2];
  245. #else
  246. w = SCM_BDIGITS (m)[nd - 1];
  247. #endif
  248. mask = (w < 0x10000
  249. ? (w < 0x100
  250. ? scm_masktab[w]
  251. : scm_masktab[w >> 8] << 8 | 0xff)
  252. : (w < 0x1000000
  253. ? scm_masktab[w >> 16] << 16 | 0xffff
  254. : scm_masktab[w >> 24] << 24 | 0xffffff));
  255. }
  256. b = scm_mkbig (nd, 0);
  257. bits = (LONG32 *) SCM_BDIGITS (b);
  258. do
  259. {
  260. i = nd;
  261. /* treat most significant digit specially */
  262. #if SIZEOF_INT == 4
  263. /* 16 bit digits */
  264. if (i & 1)
  265. {
  266. ((SCM_BIGDIG*) bits)[i - 1] = scm_the_rng.random_bits (state) & mask;
  267. i /= 2;
  268. }
  269. else
  270. #endif
  271. {
  272. /* fix most significant 32 bits */
  273. #if SIZEOF_INT == 4
  274. w = scm_the_rng.random_bits (state) & mask;
  275. ((SCM_BIGDIG*) bits)[i - 2] = w & 0xffff;
  276. ((SCM_BIGDIG*) bits)[i - 1] = w >> 16;
  277. i = i / 2 - 1;
  278. #else
  279. i /= 2;
  280. bits[--i] = scm_the_rng.random_bits (state) & mask;
  281. #endif
  282. }
  283. /* now fill up the rest of the bignum */
  284. while (i)
  285. bits[--i] = scm_the_rng.random_bits (state);
  286. b = scm_normbig (b);
  287. if (SCM_INUMP (b))
  288. return b;
  289. } while (scm_bigcomp (b, m) <= 0);
  290. return b;
  291. }
  292. /*
  293. * Scheme level representation of random states.
  294. */
  295. long scm_tc16_rstate;
  296. static SCM
  297. make_rstate (scm_rstate *state)
  298. {
  299. SCM_RETURN_NEWSMOB (scm_tc16_rstate, state);
  300. }
  301. static scm_sizet
  302. free_rstate (SCM rstate)
  303. {
  304. free (SCM_RSTATE (rstate));
  305. return scm_the_rng.rstate_size;
  306. }
  307. /*
  308. * Scheme level interface.
  309. */
  310. SCM_GLOBAL_VCELL_INIT (scm_var_random_state, "*random-state*", scm_seed_to_random_state (scm_makfrom0str ("URL:http://stat.fsu.edu/~geo/diehard.html")));
  311. SCM_DEFINE (scm_random, "random", 1, 1, 0,
  312. (SCM n, SCM state),
  313. "Return a number in [0,N).\n"
  314. "\n"
  315. "Accepts a positive integer or real n and returns a \n"
  316. "number of the same type between zero (inclusive) and \n"
  317. "N (exclusive). The values returned have a uniform \n"
  318. "distribution.\n"
  319. "\n"
  320. "The optional argument STATE must be of the type produced by\n"
  321. "`seed->random-state'. It defaults to the value of the variable\n"
  322. "*random-state*. This object is used to maintain the state of\n"
  323. "the pseudo-random-number generator and is altered as a side\n"
  324. "effect of the random operation.\n"
  325. "")
  326. #define FUNC_NAME s_scm_random
  327. {
  328. if (SCM_UNBNDP (state))
  329. state = SCM_CDR (scm_var_random_state);
  330. SCM_VALIDATE_RSTATE (2,state);
  331. if (SCM_INUMP (n))
  332. {
  333. unsigned long m = SCM_INUM (n);
  334. SCM_ASSERT_RANGE (1,n,m > 0);
  335. return SCM_MAKINUM (scm_c_random (SCM_RSTATE (state), m));
  336. }
  337. SCM_VALIDATE_NIM (1,n);
  338. if (SCM_REALP (n))
  339. return scm_make_real (SCM_REAL_VALUE (n)
  340. * scm_c_uniform01 (SCM_RSTATE (state)));
  341. SCM_VALIDATE_SMOB (1, n, big);
  342. return scm_c_random_bignum (SCM_RSTATE (state), n);
  343. }
  344. #undef FUNC_NAME
  345. SCM_DEFINE (scm_copy_random_state, "copy-random-state", 0, 1, 0,
  346. (SCM state),
  347. "Return a copy of the random state STATE.")
  348. #define FUNC_NAME s_scm_copy_random_state
  349. {
  350. if (SCM_UNBNDP (state))
  351. state = SCM_CDR (scm_var_random_state);
  352. SCM_VALIDATE_RSTATE (1,state);
  353. return make_rstate (scm_the_rng.copy_rstate (SCM_RSTATE (state)));
  354. }
  355. #undef FUNC_NAME
  356. SCM_DEFINE (scm_seed_to_random_state, "seed->random-state", 1, 0, 0,
  357. (SCM seed),
  358. "Return a new random state using SEED.")
  359. #define FUNC_NAME s_scm_seed_to_random_state
  360. {
  361. if (SCM_NUMBERP (seed))
  362. seed = scm_number_to_string (seed, SCM_UNDEFINED);
  363. SCM_VALIDATE_STRING (1,seed);
  364. return make_rstate (scm_c_make_rstate (SCM_ROCHARS (seed),
  365. SCM_LENGTH (seed)));
  366. }
  367. #undef FUNC_NAME
  368. SCM_DEFINE (scm_random_uniform, "random:uniform", 0, 1, 0,
  369. (SCM state),
  370. "Returns a uniformly distributed inexact real random number in [0,1).")
  371. #define FUNC_NAME s_scm_random_uniform
  372. {
  373. if (SCM_UNBNDP (state))
  374. state = SCM_CDR (scm_var_random_state);
  375. SCM_VALIDATE_RSTATE (1,state);
  376. return scm_make_real (scm_c_uniform01 (SCM_RSTATE (state)));
  377. }
  378. #undef FUNC_NAME
  379. SCM_DEFINE (scm_random_normal, "random:normal", 0, 1, 0,
  380. (SCM state),
  381. "Returns an inexact real in a normal distribution.\n"
  382. "The distribution used has mean 0 and standard deviation 1.\n"
  383. "For a normal distribution with mean m and standard deviation\n"
  384. "d use @code{(+ m (* d (random:normal)))}.\n"
  385. "")
  386. #define FUNC_NAME s_scm_random_normal
  387. {
  388. if (SCM_UNBNDP (state))
  389. state = SCM_CDR (scm_var_random_state);
  390. SCM_VALIDATE_RSTATE (1,state);
  391. return scm_make_real (scm_c_normal01 (SCM_RSTATE (state)));
  392. }
  393. #undef FUNC_NAME
  394. #ifdef HAVE_ARRAYS
  395. static void
  396. vector_scale (SCM v, double c)
  397. {
  398. int n = SCM_LENGTH (v);
  399. if (SCM_VECTORP (v))
  400. while (--n >= 0)
  401. SCM_REAL_VALUE (SCM_VELTS (v)[n]) *= c;
  402. else
  403. while (--n >= 0)
  404. ((double *) SCM_VELTS (v))[n] *= c;
  405. }
  406. static double
  407. vector_sum_squares (SCM v)
  408. {
  409. double x, sum = 0.0;
  410. int n = SCM_LENGTH (v);
  411. if (SCM_VECTORP (v))
  412. while (--n >= 0)
  413. {
  414. x = SCM_REAL_VALUE (SCM_VELTS (v)[n]);
  415. sum += x * x;
  416. }
  417. else
  418. while (--n >= 0)
  419. {
  420. x = ((double *) SCM_VELTS (v))[n];
  421. sum += x * x;
  422. }
  423. return sum;
  424. }
  425. /* For the uniform distribution on the solid sphere, note that in
  426. * this distribution the length r of the vector has cumulative
  427. * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
  428. * generated as r=u^(1/n).
  429. */
  430. SCM_DEFINE (scm_random_solid_sphere_x, "random:solid-sphere!", 1, 1, 0,
  431. (SCM v, SCM state),
  432. "Fills vect with inexact real random numbers\n"
  433. "the sum of whose squares is less than 1.0.\n"
  434. "Thinking of vect as coordinates in space of \n"
  435. "dimension n = (vector-length vect), the coordinates \n"
  436. "are uniformly distributed within the unit n-shere.\n"
  437. "The sum of the squares of the numbers is returned.\n"
  438. "")
  439. #define FUNC_NAME s_scm_random_solid_sphere_x
  440. {
  441. SCM_VALIDATE_VECTOR_OR_DVECTOR (1,v);
  442. if (SCM_UNBNDP (state))
  443. state = SCM_CDR (scm_var_random_state);
  444. SCM_VALIDATE_RSTATE (2,state);
  445. scm_random_normal_vector_x (v, state);
  446. vector_scale (v,
  447. pow (scm_c_uniform01 (SCM_RSTATE (state)),
  448. 1.0 / SCM_LENGTH (v))
  449. / sqrt (vector_sum_squares (v)));
  450. return SCM_UNSPECIFIED;
  451. }
  452. #undef FUNC_NAME
  453. SCM_DEFINE (scm_random_hollow_sphere_x, "random:hollow-sphere!", 1, 1, 0,
  454. (SCM v, SCM state),
  455. "Fills vect with inexact real random numbers\n"
  456. "the sum of whose squares is equal to 1.0.\n"
  457. "Thinking of vect as coordinates in space of \n"
  458. "dimension n = (vector-length vect), the coordinates\n"
  459. "are uniformly distributed over the surface of the \n"
  460. "unit n-shere.\n"
  461. "")
  462. #define FUNC_NAME s_scm_random_hollow_sphere_x
  463. {
  464. SCM_VALIDATE_VECTOR_OR_DVECTOR (1,v);
  465. if (SCM_UNBNDP (state))
  466. state = SCM_CDR (scm_var_random_state);
  467. SCM_VALIDATE_RSTATE (2,state);
  468. scm_random_normal_vector_x (v, state);
  469. vector_scale (v, 1 / sqrt (vector_sum_squares (v)));
  470. return SCM_UNSPECIFIED;
  471. }
  472. #undef FUNC_NAME
  473. SCM_DEFINE (scm_random_normal_vector_x, "random:normal-vector!", 1, 1, 0,
  474. (SCM v, SCM state),
  475. "Fills vect with inexact real random numbers that are\n"
  476. "independent and standard normally distributed\n"
  477. "(i.e., with mean 0 and variance 1).\n"
  478. "")
  479. #define FUNC_NAME s_scm_random_normal_vector_x
  480. {
  481. int n;
  482. SCM_VALIDATE_VECTOR_OR_DVECTOR (1,v);
  483. if (SCM_UNBNDP (state))
  484. state = SCM_CDR (scm_var_random_state);
  485. SCM_VALIDATE_RSTATE (2,state);
  486. n = SCM_LENGTH (v);
  487. if (SCM_VECTORP (v))
  488. while (--n >= 0)
  489. SCM_VELTS (v)[n] = scm_make_real (scm_c_normal01 (SCM_RSTATE (state)));
  490. else
  491. while (--n >= 0)
  492. ((double *) SCM_VELTS (v))[n] = scm_c_normal01 (SCM_RSTATE (state));
  493. return SCM_UNSPECIFIED;
  494. }
  495. #undef FUNC_NAME
  496. #endif /* HAVE_ARRAYS */
  497. SCM_DEFINE (scm_random_exp, "random:exp", 0, 1, 0,
  498. (SCM state),
  499. "Returns an inexact real in an exponential distribution with mean 1.\n"
  500. "For an exponential distribution with mean u use (* u (random:exp)).\n"
  501. "")
  502. #define FUNC_NAME s_scm_random_exp
  503. {
  504. if (SCM_UNBNDP (state))
  505. state = SCM_CDR (scm_var_random_state);
  506. SCM_VALIDATE_RSTATE (1,state);
  507. return scm_make_real (scm_c_exp1 (SCM_RSTATE (state)));
  508. }
  509. #undef FUNC_NAME
  510. void
  511. scm_init_random ()
  512. {
  513. int i, m;
  514. /* plug in default RNG */
  515. scm_rng rng =
  516. {
  517. sizeof (scm_i_rstate),
  518. (unsigned long (*)()) scm_i_uniform32,
  519. (void (*)()) scm_i_init_rstate,
  520. (scm_rstate *(*)()) scm_i_copy_rstate
  521. };
  522. scm_the_rng = rng;
  523. scm_tc16_rstate = scm_make_smob_type_mfpe ("random-state", 0,
  524. NULL, free_rstate, NULL, NULL);
  525. for (m = 1; m <= 0x100; m <<= 1)
  526. for (i = m >> 1; i < m; ++i)
  527. scm_masktab[i] = m - 1;
  528. #include "libguile/random.x"
  529. /* Check that the assumptions about bits per bignum digit are correct. */
  530. #if SIZEOF_INT == 4
  531. m = 16;
  532. #else
  533. m = 32;
  534. #endif
  535. if (m != SCM_BITSPERDIG)
  536. {
  537. fprintf (stderr, "Internal inconsistency: Confused about bignum digit size in random.c\n");
  538. exit (1);
  539. }
  540. scm_add_feature ("random");
  541. }
  542. /*
  543. Local Variables:
  544. c-file-style: "gnu"
  545. End:
  546. */