random.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. /* Copyright 1999-2001,2003,2005-2006,2009-2010,2012-2014,2017-2018
  2. Free Software Foundation, Inc.
  3. This file is part of Guile.
  4. Guile is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Lesser General Public License as published
  6. by the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. Guile is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  11. License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with Guile. If not, see
  14. <https://www.gnu.org/licenses/>. */
  15. /* Original Author: Mikael Djurfeldt <djurfeldt@nada.kth.se> */
  16. #ifdef HAVE_CONFIG_H
  17. # include <config.h>
  18. #endif
  19. #include <math.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <sys/types.h>
  23. #include <unistd.h>
  24. #include <gmp.h>
  25. #include "arrays.h"
  26. #include "feature.h"
  27. #include "generalized-arrays.h"
  28. #include "generalized-vectors.h"
  29. #include "gsubr.h"
  30. #include "list.h"
  31. #include "modules.h"
  32. #include "numbers.h"
  33. #include "numbers.h"
  34. #include "pairs.h"
  35. #include "smob.h"
  36. #include "srfi-4.h"
  37. #include "stime.h"
  38. #include "strings.h"
  39. #include "symbols.h"
  40. #include "variable.h"
  41. #include "vectors.h"
  42. #include "random.h"
  43. /*
  44. * A plugin interface for RNGs
  45. *
  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.
  51. *
  52. * Look in random.h and how the default generator is "plugged in" in
  53. * scm_init_random().
  54. */
  55. scm_t_rng scm_the_rng;
  56. /*
  57. * The prepackaged RNG
  58. *
  59. * This is the MWC (Multiply With Carry) random number generator
  60. * described by George Marsaglia at the Department of Statistics and
  61. * Supercomputer Computations Research Institute, The Florida State
  62. * University (http://stat.fsu.edu/~geo).
  63. *
  64. * It uses 64 bits, has a period of 4578426017172946943 (4.6e18), and
  65. * passes all tests in the DIEHARD test suite
  66. * (http://stat.fsu.edu/~geo/diehard.html)
  67. */
  68. typedef struct scm_t_i_rstate {
  69. scm_t_rstate rstate;
  70. uint32_t w;
  71. uint32_t c;
  72. } scm_t_i_rstate;
  73. #define A 2131995753UL
  74. #ifndef M_PI
  75. #define M_PI 3.14159265359
  76. #endif
  77. static uint32_t
  78. scm_i_uniform32 (scm_t_rstate *state)
  79. {
  80. scm_t_i_rstate *istate = (scm_t_i_rstate*) state;
  81. uint64_t x = (uint64_t) A * istate->w + istate->c;
  82. uint32_t w = x & 0xffffffffUL;
  83. istate->w = w;
  84. istate->c = x >> 32L;
  85. return w;
  86. }
  87. static void
  88. scm_i_init_rstate (scm_t_rstate *state, const char *seed, int n)
  89. {
  90. scm_t_i_rstate *istate = (scm_t_i_rstate*) state;
  91. uint32_t w = 0L;
  92. uint32_t c = 0L;
  93. int i, m;
  94. for (i = 0; i < n; ++i)
  95. {
  96. m = i % 8;
  97. if (m < 4)
  98. w += seed[i] << (8 * m);
  99. else
  100. c += seed[i] << (8 * (m - 4));
  101. }
  102. if ((w == 0 && c == 0) || (w == -1 && c == A - 1))
  103. ++c;
  104. istate->w = w;
  105. istate->c = c;
  106. }
  107. static scm_t_rstate *
  108. scm_i_copy_rstate (scm_t_rstate *state)
  109. {
  110. scm_t_rstate *new_state;
  111. new_state = scm_gc_malloc_pointerless (state->rng->rstate_size,
  112. "random-state");
  113. return memcpy (new_state, state, state->rng->rstate_size);
  114. }
  115. SCM_SYMBOL(scm_i_rstate_tag, "multiply-with-carry");
  116. static void
  117. scm_i_rstate_from_datum (scm_t_rstate *state, SCM value)
  118. #define FUNC_NAME "scm_i_rstate_from_datum"
  119. {
  120. scm_t_i_rstate *istate = (scm_t_i_rstate*) state;
  121. uint32_t w, c;
  122. long length;
  123. SCM_VALIDATE_LIST_COPYLEN (SCM_ARG1, value, length);
  124. SCM_ASSERT (length == 3, value, SCM_ARG1, FUNC_NAME);
  125. SCM_ASSERT (scm_is_eq (SCM_CAR (value), scm_i_rstate_tag),
  126. value, SCM_ARG1, FUNC_NAME);
  127. SCM_VALIDATE_UINT_COPY (SCM_ARG1, SCM_CADR (value), w);
  128. SCM_VALIDATE_UINT_COPY (SCM_ARG1, SCM_CADDR (value), c);
  129. istate->w = w;
  130. istate->c = c;
  131. }
  132. #undef FUNC_NAME
  133. static SCM
  134. scm_i_rstate_to_datum (scm_t_rstate *state)
  135. {
  136. scm_t_i_rstate *istate = (scm_t_i_rstate*) state;
  137. return scm_list_3 (scm_i_rstate_tag,
  138. scm_from_uint32 (istate->w),
  139. scm_from_uint32 (istate->c));
  140. }
  141. /*
  142. * Random number library functions
  143. */
  144. scm_t_rstate *
  145. scm_c_make_rstate (const char *seed, int n)
  146. {
  147. scm_t_rstate *state;
  148. state = scm_gc_malloc_pointerless (scm_the_rng.rstate_size,
  149. "random-state");
  150. state->rng = &scm_the_rng;
  151. state->normal_next = 0.0;
  152. state->rng->init_rstate (state, seed, n);
  153. return state;
  154. }
  155. scm_t_rstate *
  156. scm_c_rstate_from_datum (SCM datum)
  157. {
  158. scm_t_rstate *state;
  159. state = scm_gc_malloc_pointerless (scm_the_rng.rstate_size,
  160. "random-state");
  161. state->rng = &scm_the_rng;
  162. state->normal_next = 0.0;
  163. state->rng->from_datum (state, datum);
  164. return state;
  165. }
  166. scm_t_rstate *
  167. scm_c_default_rstate ()
  168. #define FUNC_NAME "scm_c_default_rstate"
  169. {
  170. SCM state = SCM_VARIABLE_REF (scm_var_random_state);
  171. if (!SCM_RSTATEP (state))
  172. SCM_MISC_ERROR ("*random-state* contains bogus random state", SCM_EOL);
  173. return SCM_RSTATE (state);
  174. }
  175. #undef FUNC_NAME
  176. double
  177. scm_c_uniform01 (scm_t_rstate *state)
  178. {
  179. double x = (double) state->rng->random_bits (state) / (double) 0xffffffffUL;
  180. return ((x + (double) state->rng->random_bits (state))
  181. / (double) 0xffffffffUL);
  182. }
  183. double
  184. scm_c_normal01 (scm_t_rstate *state)
  185. {
  186. if (state->normal_next != 0.0)
  187. {
  188. double ret = state->normal_next;
  189. state->normal_next = 0.0;
  190. return ret;
  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->normal_next = r * cos (a);
  199. return n;
  200. }
  201. }
  202. double
  203. scm_c_exp1 (scm_t_rstate *state)
  204. {
  205. return - log (scm_c_uniform01 (state));
  206. }
  207. unsigned char scm_masktab[256];
  208. static inline uint32_t
  209. scm_i_mask32 (uint32_t m)
  210. {
  211. return (m < 0x100
  212. ? scm_masktab[m]
  213. : (m < 0x10000
  214. ? scm_masktab[m >> 8] << 8 | 0xff
  215. : (m < 0x1000000
  216. ? scm_masktab[m >> 16] << 16 | 0xffff
  217. : ((uint32_t) scm_masktab[m >> 24]) << 24 | 0xffffff)));
  218. }
  219. uint32_t
  220. scm_c_random (scm_t_rstate *state, uint32_t m)
  221. {
  222. uint32_t r, mask = scm_i_mask32 (m);
  223. while ((r = state->rng->random_bits (state) & mask) >= m);
  224. return r;
  225. }
  226. uint64_t
  227. scm_c_random64 (scm_t_rstate *state, uint64_t m)
  228. {
  229. uint64_t r;
  230. uint32_t mask;
  231. if (m <= UINT32_MAX)
  232. return scm_c_random (state, (uint32_t) m);
  233. mask = scm_i_mask32 (m >> 32);
  234. while ((r = ((uint64_t) (state->rng->random_bits (state) & mask) << 32)
  235. | state->rng->random_bits (state)) >= m)
  236. ;
  237. return r;
  238. }
  239. /*
  240. SCM scm_c_random_bignum (scm_t_rstate *state, SCM m)
  241. Takes a random state (source of random bits) and a bignum m.
  242. Returns a bignum b, 0 <= b < m.
  243. It does this by allocating a bignum b with as many base 65536 digits
  244. as m, filling b with random bits (in 32 bit chunks) up to the most
  245. significant 1 in m, and, finally checking if the resultant b is too
  246. large (>= m). If too large, we simply repeat the process again. (It
  247. is important to throw away all generated random bits if b >= m,
  248. otherwise we'll end up with a distorted distribution.)
  249. */
  250. SCM
  251. scm_c_random_bignum (scm_t_rstate *state, SCM m)
  252. {
  253. SCM result = scm_i_mkbig ();
  254. const size_t m_bits = mpz_sizeinbase (SCM_I_BIG_MPZ (m), 2);
  255. /* how many bits would only partially fill the last uint32_t? */
  256. const size_t end_bits = m_bits % (sizeof (uint32_t) * SCM_CHAR_BIT);
  257. uint32_t *random_chunks = NULL;
  258. const uint32_t num_full_chunks =
  259. m_bits / (sizeof (uint32_t) * SCM_CHAR_BIT);
  260. const uint32_t 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);
  263. random_chunks =
  264. (uint32_t *) scm_gc_calloc (num_chunks * sizeof (uint32_t),
  265. "random bignum chunks");
  266. do
  267. {
  268. uint32_t *current_chunk = random_chunks + (num_chunks - 1);
  269. uint32_t chunks_left = num_chunks;
  270. mpz_set_ui (SCM_I_BIG_MPZ (result), 0);
  271. if (end_bits)
  272. {
  273. /* generate a mask with ones in the end_bits position, i.e. if
  274. end_bits is 3, then we'd have a mask of ...0000000111 */
  275. const uint32_t rndbits = state->rng->random_bits (state);
  276. int rshift = (sizeof (uint32_t) * SCM_CHAR_BIT) - end_bits;
  277. uint32_t mask = ((uint32_t)-1) >> rshift;
  278. uint32_t highest_bits = rndbits & mask;
  279. *current_chunk-- = highest_bits;
  280. chunks_left--;
  281. }
  282. while (chunks_left)
  283. {
  284. /* now fill in the remaining uint32_t sized chunks */
  285. *current_chunk-- = state->rng->random_bits (state);
  286. chunks_left--;
  287. }
  288. mpz_import (SCM_I_BIG_MPZ (result),
  289. num_chunks,
  290. -1,
  291. sizeof (uint32_t),
  292. 0,
  293. 0,
  294. random_chunks);
  295. /* if result >= m, regenerate it (it is important to regenerate
  296. all bits in order not to get a distorted distribution) */
  297. } while (mpz_cmp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (m)) >= 0);
  298. scm_gc_free (random_chunks,
  299. num_chunks * sizeof (uint32_t),
  300. "random bignum chunks");
  301. return scm_i_normbig (result);
  302. }
  303. /*
  304. * Scheme level representation of random states.
  305. */
  306. scm_t_bits scm_tc16_rstate;
  307. static SCM
  308. make_rstate (scm_t_rstate *state)
  309. {
  310. SCM_RETURN_NEWSMOB (scm_tc16_rstate, state);
  311. }
  312. /*
  313. * Scheme level interface.
  314. */
  315. 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")));
  316. SCM_DEFINE (scm_random, "random", 1, 1, 0,
  317. (SCM n, SCM state),
  318. "Return a number in [0, N).\n"
  319. "\n"
  320. "Accepts a positive integer or real n and returns a\n"
  321. "number of the same type between zero (inclusive) and\n"
  322. "N (exclusive). The values returned have a uniform\n"
  323. "distribution.\n"
  324. "\n"
  325. "The optional argument @var{state} must be of the type produced\n"
  326. "by @code{seed->random-state}. It defaults to the value of the\n"
  327. "variable @var{*random-state*}. This object is used to maintain\n"
  328. "the state of the pseudo-random-number generator and is altered\n"
  329. "as a side effect of the random operation.")
  330. #define FUNC_NAME s_scm_random
  331. {
  332. if (SCM_UNBNDP (state))
  333. state = SCM_VARIABLE_REF (scm_var_random_state);
  334. SCM_VALIDATE_RSTATE (2, state);
  335. if (SCM_I_INUMP (n))
  336. {
  337. scm_t_bits m = (scm_t_bits) SCM_I_INUM (n);
  338. SCM_ASSERT_RANGE (1, n, SCM_I_INUM (n) > 0);
  339. #if SCM_SIZEOF_UINTPTR_T <= 4
  340. return scm_from_uint32 (scm_c_random (SCM_RSTATE (state),
  341. (uint32_t) m));
  342. #elif SCM_SIZEOF_UINTPTR_T <= 8
  343. return scm_from_uint64 (scm_c_random64 (SCM_RSTATE (state),
  344. (uint64_t) m));
  345. #else
  346. #error "Cannot deal with this platform's scm_t_bits size"
  347. #endif
  348. }
  349. if (SCM_REALP (n))
  350. return scm_from_double (SCM_REAL_VALUE (n)
  351. * scm_c_uniform01 (SCM_RSTATE (state)));
  352. if (!SCM_BIGP (n))
  353. SCM_WRONG_TYPE_ARG (1, n);
  354. return scm_c_random_bignum (SCM_RSTATE (state), n);
  355. }
  356. #undef FUNC_NAME
  357. SCM_DEFINE (scm_copy_random_state, "copy-random-state", 0, 1, 0,
  358. (SCM state),
  359. "Return a copy of the random state @var{state}.")
  360. #define FUNC_NAME s_scm_copy_random_state
  361. {
  362. if (SCM_UNBNDP (state))
  363. state = SCM_VARIABLE_REF (scm_var_random_state);
  364. SCM_VALIDATE_RSTATE (1, state);
  365. return make_rstate (SCM_RSTATE (state)->rng->copy_rstate (SCM_RSTATE (state)));
  366. }
  367. #undef FUNC_NAME
  368. SCM_DEFINE (scm_seed_to_random_state, "seed->random-state", 1, 0, 0,
  369. (SCM seed),
  370. "Return a new random state using @var{seed}.")
  371. #define FUNC_NAME s_scm_seed_to_random_state
  372. {
  373. SCM res;
  374. if (SCM_NUMBERP (seed))
  375. seed = scm_number_to_string (seed, SCM_UNDEFINED);
  376. SCM_VALIDATE_STRING (1, seed);
  377. res = make_rstate (scm_c_make_rstate (scm_i_string_chars (seed),
  378. scm_i_string_length (seed)));
  379. scm_remember_upto_here_1 (seed);
  380. return res;
  381. }
  382. #undef FUNC_NAME
  383. SCM_DEFINE (scm_datum_to_random_state, "datum->random-state", 1, 0, 0,
  384. (SCM datum),
  385. "Return a new random state using @var{datum}, which should have\n"
  386. "been obtained from @code{random-state->datum}.")
  387. #define FUNC_NAME s_scm_datum_to_random_state
  388. {
  389. return make_rstate (scm_c_rstate_from_datum (datum));
  390. }
  391. #undef FUNC_NAME
  392. SCM_DEFINE (scm_random_state_to_datum, "random-state->datum", 1, 0, 0,
  393. (SCM state),
  394. "Return a datum representation of @var{state} that may be\n"
  395. "written out and read back with the Scheme reader.")
  396. #define FUNC_NAME s_scm_random_state_to_datum
  397. {
  398. SCM_VALIDATE_RSTATE (1, state);
  399. return SCM_RSTATE (state)->rng->to_datum (SCM_RSTATE (state));
  400. }
  401. #undef FUNC_NAME
  402. SCM_DEFINE (scm_random_uniform, "random:uniform", 0, 1, 0,
  403. (SCM state),
  404. "Return a uniformly distributed inexact real random number in\n"
  405. "[0,1).")
  406. #define FUNC_NAME s_scm_random_uniform
  407. {
  408. if (SCM_UNBNDP (state))
  409. state = SCM_VARIABLE_REF (scm_var_random_state);
  410. SCM_VALIDATE_RSTATE (1, state);
  411. return scm_from_double (scm_c_uniform01 (SCM_RSTATE (state)));
  412. }
  413. #undef FUNC_NAME
  414. SCM_DEFINE (scm_random_normal, "random:normal", 0, 1, 0,
  415. (SCM state),
  416. "Return an inexact real in a normal distribution. The\n"
  417. "distribution used has mean 0 and standard deviation 1. For a\n"
  418. "normal distribution with mean m and standard deviation d use\n"
  419. "@code{(+ m (* d (random:normal)))}.")
  420. #define FUNC_NAME s_scm_random_normal
  421. {
  422. if (SCM_UNBNDP (state))
  423. state = SCM_VARIABLE_REF (scm_var_random_state);
  424. SCM_VALIDATE_RSTATE (1, state);
  425. return scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
  426. }
  427. #undef FUNC_NAME
  428. static void
  429. vector_scale_x (SCM v, double c)
  430. {
  431. scm_t_array_handle handle;
  432. scm_t_array_dim const * dims;
  433. ssize_t i, inc, ubnd;
  434. scm_array_get_handle (v, &handle);
  435. dims = scm_array_handle_dims (&handle);
  436. if (1 == scm_array_handle_rank (&handle))
  437. {
  438. ubnd = dims[0].ubnd;
  439. inc = dims[0].inc;
  440. if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_F64)
  441. {
  442. double *elts = (double *)(handle.writable_elements) + handle.base;
  443. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  444. *elts *= c;
  445. return;
  446. }
  447. else if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_SCM)
  448. {
  449. SCM *elts = (SCM *)(handle.writable_elements) + handle.base;
  450. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  451. SCM_REAL_VALUE (*elts) *= c;
  452. return;
  453. }
  454. }
  455. scm_array_handle_release (&handle);
  456. scm_misc_error (NULL, "must be a rank-1 array of type #t or 'f64", scm_list_1 (v));
  457. }
  458. static double
  459. vector_sum_squares (SCM v)
  460. {
  461. double x, sum = 0.0;
  462. scm_t_array_handle handle;
  463. scm_t_array_dim const * dims;
  464. ssize_t i, inc, ubnd;
  465. scm_array_get_handle (v, &handle);
  466. dims = scm_array_handle_dims (&handle);
  467. if (1 == scm_array_handle_rank (&handle))
  468. {
  469. ubnd = dims[0].ubnd;
  470. inc = dims[0].inc;
  471. if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_F64)
  472. {
  473. const double *elts = (const double *)(handle.elements) + handle.base;
  474. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  475. {
  476. x = *elts;
  477. sum += x * x;
  478. }
  479. return sum;
  480. }
  481. else if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_SCM)
  482. {
  483. const SCM *elts = (const SCM *)(handle.elements) + handle.base;
  484. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  485. {
  486. x = SCM_REAL_VALUE (*elts);
  487. sum += x * x;
  488. }
  489. return sum;
  490. }
  491. }
  492. scm_array_handle_release (&handle);
  493. scm_misc_error (NULL, "must be an array of type #t or 'f64", scm_list_1 (v));
  494. }
  495. /* For the uniform distribution on the solid sphere, note that in
  496. * this distribution the length r of the vector has cumulative
  497. * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
  498. * generated as r=u^(1/n).
  499. */
  500. SCM_DEFINE (scm_random_solid_sphere_x, "random:solid-sphere!", 1, 1, 0,
  501. (SCM v, SCM state),
  502. "Fills @var{vect} with inexact real random numbers the sum of\n"
  503. "whose squares is less than 1.0. Thinking of @var{vect} as\n"
  504. "coordinates in space of dimension @var{n} @math{=}\n"
  505. "@code{(vector-length @var{vect})}, the coordinates are\n"
  506. "uniformly distributed within the unit @var{n}-sphere.")
  507. #define FUNC_NAME s_scm_random_solid_sphere_x
  508. {
  509. if (SCM_UNBNDP (state))
  510. state = SCM_VARIABLE_REF (scm_var_random_state);
  511. SCM_VALIDATE_RSTATE (2, state);
  512. scm_random_normal_vector_x (v, state);
  513. vector_scale_x (v,
  514. pow (scm_c_uniform01 (SCM_RSTATE (state)),
  515. 1.0 / scm_c_array_length (v))
  516. / sqrt (vector_sum_squares (v)));
  517. return SCM_UNSPECIFIED;
  518. }
  519. #undef FUNC_NAME
  520. SCM_DEFINE (scm_random_hollow_sphere_x, "random:hollow-sphere!", 1, 1, 0,
  521. (SCM v, SCM state),
  522. "Fills vect with inexact real random numbers\n"
  523. "the sum of whose squares is equal to 1.0.\n"
  524. "Thinking of vect as coordinates in space of\n"
  525. "dimension n = (vector-length vect), the coordinates\n"
  526. "are uniformly distributed over the surface of the\n"
  527. "unit n-sphere.")
  528. #define FUNC_NAME s_scm_random_hollow_sphere_x
  529. {
  530. if (SCM_UNBNDP (state))
  531. state = SCM_VARIABLE_REF (scm_var_random_state);
  532. SCM_VALIDATE_RSTATE (2, state);
  533. scm_random_normal_vector_x (v, state);
  534. vector_scale_x (v, 1 / sqrt (vector_sum_squares (v)));
  535. return SCM_UNSPECIFIED;
  536. }
  537. #undef FUNC_NAME
  538. SCM_DEFINE (scm_random_normal_vector_x, "random:normal-vector!", 1, 1, 0,
  539. (SCM v, SCM state),
  540. "Fills vect with inexact real random numbers that are\n"
  541. "independent and standard normally distributed\n"
  542. "(i.e., with mean 0 and variance 1).")
  543. #define FUNC_NAME s_scm_random_normal_vector_x
  544. {
  545. scm_t_array_handle handle;
  546. scm_t_array_dim const * dims;
  547. ssize_t i;
  548. if (SCM_UNBNDP (state))
  549. state = SCM_VARIABLE_REF (scm_var_random_state);
  550. SCM_VALIDATE_RSTATE (2, state);
  551. scm_array_get_handle (v, &handle);
  552. if (1 != scm_array_handle_rank (&handle))
  553. {
  554. scm_array_handle_release (&handle);
  555. scm_wrong_type_arg_msg (NULL, 0, v, "rank 1 array");
  556. }
  557. dims = scm_array_handle_dims (&handle);
  558. if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_SCM)
  559. {
  560. SCM *elts = scm_array_handle_writable_elements (&handle);
  561. for (i = dims->lbnd; i <= dims->ubnd; i++, elts += dims->inc)
  562. *elts = scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
  563. }
  564. else
  565. {
  566. /* must be a f64vector. */
  567. double *elts = scm_array_handle_f64_writable_elements (&handle);
  568. for (i = dims->lbnd; i <= dims->ubnd; i++, elts += dims->inc)
  569. *elts = scm_c_normal01 (SCM_RSTATE (state));
  570. }
  571. scm_array_handle_release (&handle);
  572. return SCM_UNSPECIFIED;
  573. }
  574. #undef FUNC_NAME
  575. SCM_DEFINE (scm_random_exp, "random:exp", 0, 1, 0,
  576. (SCM state),
  577. "Return an inexact real in an exponential distribution with mean\n"
  578. "1. For an exponential distribution with mean u use (* u\n"
  579. "(random:exp)).")
  580. #define FUNC_NAME s_scm_random_exp
  581. {
  582. if (SCM_UNBNDP (state))
  583. state = SCM_VARIABLE_REF (scm_var_random_state);
  584. SCM_VALIDATE_RSTATE (1, state);
  585. return scm_from_double (scm_c_exp1 (SCM_RSTATE (state)));
  586. }
  587. #undef FUNC_NAME
  588. /* Return a new random-state seeded from the time, date, process ID, an
  589. address from a freshly allocated heap cell, an address from the local
  590. stack frame, and a high-resolution timer if available. This is only
  591. to be used as a last resort, when no better source of entropy is
  592. available. */
  593. static SCM
  594. random_state_of_last_resort (void)
  595. {
  596. SCM state;
  597. SCM time_of_day = scm_gettimeofday ();
  598. SCM sources = scm_list_n
  599. (scm_from_unsigned_integer (SCM_UNPACK (time_of_day)), /* heap addr */
  600. /* Avoid scm_getpid, since it depends on HAVE_POSIX. */
  601. scm_from_unsigned_integer (getpid ()), /* process ID */
  602. scm_get_internal_real_time (), /* high-resolution process timer */
  603. scm_from_unsigned_integer ((scm_t_bits) &time_of_day), /* stack addr */
  604. scm_car (time_of_day), /* seconds since midnight 1970-01-01 UTC */
  605. scm_cdr (time_of_day), /* microsecond component of the above clock */
  606. SCM_UNDEFINED);
  607. /* Concatenate the sources bitwise to form the seed */
  608. SCM seed = SCM_INUM0;
  609. while (scm_is_pair (sources))
  610. {
  611. seed = scm_logxor (seed, scm_ash (scm_car (sources),
  612. scm_integer_length (seed)));
  613. sources = scm_cdr (sources);
  614. }
  615. /* FIXME The following code belongs in `scm_seed_to_random_state',
  616. and here we should simply do:
  617. return scm_seed_to_random_state (seed);
  618. Unfortunately, `scm_seed_to_random_state' only preserves around 32
  619. bits of entropy from the provided seed. I don't know if it's okay
  620. to fix that in 2.0, so for now we have this workaround. */
  621. {
  622. int i, len;
  623. unsigned char *buf;
  624. len = scm_to_int (scm_ceiling_quotient (scm_integer_length (seed),
  625. SCM_I_MAKINUM (8)));
  626. buf = (unsigned char *) malloc (len);
  627. for (i = len-1; i >= 0; --i)
  628. {
  629. buf[i] = scm_to_int (scm_logand (seed, SCM_I_MAKINUM (255)));
  630. seed = scm_ash (seed, SCM_I_MAKINUM (-8));
  631. }
  632. state = make_rstate (scm_c_make_rstate ((char *) buf, len));
  633. free (buf);
  634. }
  635. return state;
  636. }
  637. /* Attempt to fill buffer with random bytes from /dev/urandom.
  638. Return 1 if successful, else return 0. */
  639. static int
  640. read_dev_urandom (unsigned char *buf, size_t len)
  641. {
  642. size_t res = 0;
  643. FILE *f = fopen ("/dev/urandom", "r");
  644. if (f)
  645. {
  646. res = fread(buf, 1, len, f);
  647. fclose (f);
  648. }
  649. return (res == len);
  650. }
  651. /* Fill a buffer with random bytes seeded from a platform-specific
  652. source of entropy. /dev/urandom is used if available. Note that
  653. this function provides no guarantees about the amount of entropy
  654. present in the returned bytes. */
  655. void
  656. scm_i_random_bytes_from_platform (unsigned char *buf, size_t len)
  657. {
  658. if (read_dev_urandom (buf, len))
  659. return;
  660. else /* FIXME: support other platform sources */
  661. {
  662. /* When all else fails, use this (rather weak) fallback */
  663. SCM random_state = random_state_of_last_resort ();
  664. int i;
  665. for (i = len-1; i >= 0; --i)
  666. buf[i] = scm_to_int (scm_random (SCM_I_MAKINUM (256), random_state));
  667. }
  668. }
  669. SCM_DEFINE (scm_random_state_from_platform, "random-state-from-platform", 0, 0, 0,
  670. (void),
  671. "Construct a new random state seeded from a platform-specific\n\
  672. source of entropy, appropriate for use in non-security-critical applications.")
  673. #define FUNC_NAME s_scm_random_state_from_platform
  674. {
  675. unsigned char buf[32];
  676. if (read_dev_urandom (buf, sizeof(buf)))
  677. return make_rstate (scm_c_make_rstate ((char *) buf, sizeof(buf)));
  678. else
  679. return random_state_of_last_resort ();
  680. }
  681. #undef FUNC_NAME
  682. void
  683. scm_init_random ()
  684. {
  685. int i, m;
  686. /* plug in default RNG */
  687. scm_t_rng rng =
  688. {
  689. sizeof (scm_t_i_rstate),
  690. scm_i_uniform32,
  691. scm_i_init_rstate,
  692. scm_i_copy_rstate,
  693. scm_i_rstate_from_datum,
  694. scm_i_rstate_to_datum
  695. };
  696. scm_the_rng = rng;
  697. scm_tc16_rstate = scm_make_smob_type ("random-state", 0);
  698. for (m = 1; m <= 0x100; m <<= 1)
  699. for (i = m >> 1; i < m; ++i)
  700. scm_masktab[i] = m - 1;
  701. #include "random.x"
  702. scm_add_feature ("random");
  703. }