random.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /* Copyright 1999-2001,2003,2005-2006,2009-2010,2012-2014,2017-2019
  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*",
  316. scm_seed_to_random_state
  317. (scm_from_utf8_string
  318. ("URL:http://stat.fsu.edu/~geo/diehard.html")));
  319. SCM_DEFINE (scm_random, "random", 1, 1, 0,
  320. (SCM n, SCM state),
  321. "Return a number in [0, N).\n"
  322. "\n"
  323. "Accepts a positive integer or real n and returns a\n"
  324. "number of the same type between zero (inclusive) and\n"
  325. "N (exclusive). The values returned have a uniform\n"
  326. "distribution.\n"
  327. "\n"
  328. "The optional argument @var{state} must be of the type produced\n"
  329. "by @code{seed->random-state}. It defaults to the value of the\n"
  330. "variable @var{*random-state*}. This object is used to maintain\n"
  331. "the state of the pseudo-random-number generator and is altered\n"
  332. "as a side effect of the random operation.")
  333. #define FUNC_NAME s_scm_random
  334. {
  335. if (SCM_UNBNDP (state))
  336. state = SCM_VARIABLE_REF (scm_var_random_state);
  337. SCM_VALIDATE_RSTATE (2, state);
  338. if (SCM_I_INUMP (n))
  339. {
  340. scm_t_bits m = (scm_t_bits) SCM_I_INUM (n);
  341. SCM_ASSERT_RANGE (1, n, SCM_I_INUM (n) > 0);
  342. #if SCM_SIZEOF_UINTPTR_T <= 4
  343. return scm_from_uint32 (scm_c_random (SCM_RSTATE (state),
  344. (uint32_t) m));
  345. #elif SCM_SIZEOF_UINTPTR_T <= 8
  346. return scm_from_uint64 (scm_c_random64 (SCM_RSTATE (state),
  347. (uint64_t) m));
  348. #else
  349. #error "Cannot deal with this platform's scm_t_bits size"
  350. #endif
  351. }
  352. if (SCM_REALP (n))
  353. return scm_from_double (SCM_REAL_VALUE (n)
  354. * scm_c_uniform01 (SCM_RSTATE (state)));
  355. if (!SCM_BIGP (n))
  356. SCM_WRONG_TYPE_ARG (1, n);
  357. return scm_c_random_bignum (SCM_RSTATE (state), n);
  358. }
  359. #undef FUNC_NAME
  360. SCM_DEFINE (scm_copy_random_state, "copy-random-state", 0, 1, 0,
  361. (SCM state),
  362. "Return a copy of the random state @var{state}.")
  363. #define FUNC_NAME s_scm_copy_random_state
  364. {
  365. if (SCM_UNBNDP (state))
  366. state = SCM_VARIABLE_REF (scm_var_random_state);
  367. SCM_VALIDATE_RSTATE (1, state);
  368. return make_rstate (SCM_RSTATE (state)->rng->copy_rstate (SCM_RSTATE (state)));
  369. }
  370. #undef FUNC_NAME
  371. SCM_DEFINE (scm_seed_to_random_state, "seed->random-state", 1, 0, 0,
  372. (SCM seed),
  373. "Return a new random state using @var{seed}.")
  374. #define FUNC_NAME s_scm_seed_to_random_state
  375. {
  376. SCM res;
  377. char *c_str;
  378. size_t len;
  379. if (SCM_NUMBERP (seed))
  380. seed = scm_number_to_string (seed, SCM_UNDEFINED);
  381. SCM_VALIDATE_STRING (1, seed);
  382. if (scm_i_is_narrow_string (seed))
  383. /* This special case of a narrow string, where latin1 is used, is
  384. for backward compatibility during the 2.2 stable series. In
  385. future major releases, we should use UTF-8 uniformly. */
  386. c_str = scm_to_latin1_stringn (seed, &len);
  387. else
  388. c_str = scm_to_utf8_stringn (seed, &len);
  389. /* 'scm_to_*_stringn' returns a 'size_t' for the length in bytes, but
  390. 'scm_c_make_rstate' accepts an 'int'. Make sure the length fits in
  391. an 'int'. */
  392. if (len > INT_MAX)
  393. {
  394. free (c_str);
  395. SCM_OUT_OF_RANGE (1, seed);
  396. }
  397. res = make_rstate (scm_c_make_rstate (c_str, len));
  398. free (c_str);
  399. scm_remember_upto_here_1 (seed);
  400. return res;
  401. }
  402. #undef FUNC_NAME
  403. SCM_DEFINE (scm_datum_to_random_state, "datum->random-state", 1, 0, 0,
  404. (SCM datum),
  405. "Return a new random state using @var{datum}, which should have\n"
  406. "been obtained from @code{random-state->datum}.")
  407. #define FUNC_NAME s_scm_datum_to_random_state
  408. {
  409. return make_rstate (scm_c_rstate_from_datum (datum));
  410. }
  411. #undef FUNC_NAME
  412. SCM_DEFINE (scm_random_state_to_datum, "random-state->datum", 1, 0, 0,
  413. (SCM state),
  414. "Return a datum representation of @var{state} that may be\n"
  415. "written out and read back with the Scheme reader.")
  416. #define FUNC_NAME s_scm_random_state_to_datum
  417. {
  418. SCM_VALIDATE_RSTATE (1, state);
  419. return SCM_RSTATE (state)->rng->to_datum (SCM_RSTATE (state));
  420. }
  421. #undef FUNC_NAME
  422. SCM_DEFINE (scm_random_uniform, "random:uniform", 0, 1, 0,
  423. (SCM state),
  424. "Return a uniformly distributed inexact real random number in\n"
  425. "[0,1).")
  426. #define FUNC_NAME s_scm_random_uniform
  427. {
  428. if (SCM_UNBNDP (state))
  429. state = SCM_VARIABLE_REF (scm_var_random_state);
  430. SCM_VALIDATE_RSTATE (1, state);
  431. return scm_from_double (scm_c_uniform01 (SCM_RSTATE (state)));
  432. }
  433. #undef FUNC_NAME
  434. SCM_DEFINE (scm_random_normal, "random:normal", 0, 1, 0,
  435. (SCM state),
  436. "Return an inexact real in a normal distribution. The\n"
  437. "distribution used has mean 0 and standard deviation 1. For a\n"
  438. "normal distribution with mean m and standard deviation d use\n"
  439. "@code{(+ m (* d (random:normal)))}.")
  440. #define FUNC_NAME s_scm_random_normal
  441. {
  442. if (SCM_UNBNDP (state))
  443. state = SCM_VARIABLE_REF (scm_var_random_state);
  444. SCM_VALIDATE_RSTATE (1, state);
  445. return scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
  446. }
  447. #undef FUNC_NAME
  448. static void
  449. vector_scale_x (SCM v, double c)
  450. {
  451. scm_t_array_handle handle;
  452. scm_t_array_dim const * dims;
  453. ssize_t i, inc, ubnd;
  454. scm_array_get_handle (v, &handle);
  455. dims = scm_array_handle_dims (&handle);
  456. if (1 == scm_array_handle_rank (&handle))
  457. {
  458. ubnd = dims[0].ubnd;
  459. inc = dims[0].inc;
  460. if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_F64)
  461. {
  462. double *elts = (double *)(handle.writable_elements) + handle.base;
  463. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  464. *elts *= c;
  465. return;
  466. }
  467. else if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_SCM)
  468. {
  469. SCM cc = scm_from_double (c);
  470. SCM *elts = (SCM *)(handle.writable_elements) + handle.base;
  471. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  472. *elts = scm_product (*elts, cc);
  473. return;
  474. }
  475. }
  476. scm_array_handle_release (&handle);
  477. scm_misc_error (NULL, "must be a rank-1 array of type #t or 'f64", scm_list_1 (v));
  478. }
  479. static double
  480. vector_sum_squares (SCM v)
  481. {
  482. double x, sum = 0.0;
  483. scm_t_array_handle handle;
  484. scm_t_array_dim const * dims;
  485. ssize_t i, inc, ubnd;
  486. scm_array_get_handle (v, &handle);
  487. dims = scm_array_handle_dims (&handle);
  488. if (1 == scm_array_handle_rank (&handle))
  489. {
  490. ubnd = dims[0].ubnd;
  491. inc = dims[0].inc;
  492. if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_F64)
  493. {
  494. const double *elts = (const double *)(handle.elements) + handle.base;
  495. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  496. {
  497. x = *elts;
  498. sum += x * x;
  499. }
  500. return sum;
  501. }
  502. else if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_SCM)
  503. {
  504. const SCM *elts = (const SCM *)(handle.elements) + handle.base;
  505. for (i = dims[0].lbnd; i <= ubnd; ++i, elts += inc)
  506. {
  507. x = SCM_REAL_VALUE (*elts);
  508. sum += x * x;
  509. }
  510. return sum;
  511. }
  512. }
  513. scm_array_handle_release (&handle);
  514. scm_misc_error (NULL, "must be an array of type #t or 'f64", scm_list_1 (v));
  515. }
  516. /* For the uniform distribution on the solid sphere, note that in
  517. * this distribution the length r of the vector has cumulative
  518. * distribution r^n; i.e., u=r^n is uniform [0,1], so r can be
  519. * generated as r=u^(1/n).
  520. */
  521. SCM_DEFINE (scm_random_solid_sphere_x, "random:solid-sphere!", 1, 1, 0,
  522. (SCM v, SCM state),
  523. "Fills @var{vect} with inexact real random numbers the sum of\n"
  524. "whose squares is less than 1.0. Thinking of @var{vect} as\n"
  525. "coordinates in space of dimension @var{n} @math{=}\n"
  526. "@code{(vector-length @var{vect})}, the coordinates are\n"
  527. "uniformly distributed within the unit @var{n}-sphere.")
  528. #define FUNC_NAME s_scm_random_solid_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,
  535. pow (scm_c_uniform01 (SCM_RSTATE (state)),
  536. 1.0 / scm_c_array_length (v))
  537. / sqrt (vector_sum_squares (v)));
  538. return SCM_UNSPECIFIED;
  539. }
  540. #undef FUNC_NAME
  541. SCM_DEFINE (scm_random_hollow_sphere_x, "random:hollow-sphere!", 1, 1, 0,
  542. (SCM v, SCM state),
  543. "Fills vect with inexact real random numbers\n"
  544. "the sum of whose squares is equal to 1.0.\n"
  545. "Thinking of vect as coordinates in space of\n"
  546. "dimension n = (vector-length vect), the coordinates\n"
  547. "are uniformly distributed over the surface of the\n"
  548. "unit n-sphere.")
  549. #define FUNC_NAME s_scm_random_hollow_sphere_x
  550. {
  551. if (SCM_UNBNDP (state))
  552. state = SCM_VARIABLE_REF (scm_var_random_state);
  553. SCM_VALIDATE_RSTATE (2, state);
  554. scm_random_normal_vector_x (v, state);
  555. vector_scale_x (v, 1 / sqrt (vector_sum_squares (v)));
  556. return SCM_UNSPECIFIED;
  557. }
  558. #undef FUNC_NAME
  559. SCM_DEFINE (scm_random_normal_vector_x, "random:normal-vector!", 1, 1, 0,
  560. (SCM v, SCM state),
  561. "Fills vect with inexact real random numbers that are\n"
  562. "independent and standard normally distributed\n"
  563. "(i.e., with mean 0 and variance 1).")
  564. #define FUNC_NAME s_scm_random_normal_vector_x
  565. {
  566. scm_t_array_handle handle;
  567. scm_t_array_dim const * dims;
  568. ssize_t i;
  569. if (SCM_UNBNDP (state))
  570. state = SCM_VARIABLE_REF (scm_var_random_state);
  571. SCM_VALIDATE_RSTATE (2, state);
  572. scm_array_get_handle (v, &handle);
  573. if (1 != scm_array_handle_rank (&handle))
  574. {
  575. scm_array_handle_release (&handle);
  576. scm_wrong_type_arg_msg (NULL, 0, v, "rank 1 array");
  577. }
  578. dims = scm_array_handle_dims (&handle);
  579. if (handle.element_type == SCM_ARRAY_ELEMENT_TYPE_SCM)
  580. {
  581. SCM *elts = scm_array_handle_writable_elements (&handle);
  582. for (i = dims->lbnd; i <= dims->ubnd; i++, elts += dims->inc)
  583. *elts = scm_from_double (scm_c_normal01 (SCM_RSTATE (state)));
  584. }
  585. else
  586. {
  587. /* must be a f64vector. */
  588. double *elts = scm_array_handle_f64_writable_elements (&handle);
  589. for (i = dims->lbnd; i <= dims->ubnd; i++, elts += dims->inc)
  590. *elts = scm_c_normal01 (SCM_RSTATE (state));
  591. }
  592. scm_array_handle_release (&handle);
  593. return SCM_UNSPECIFIED;
  594. }
  595. #undef FUNC_NAME
  596. SCM_DEFINE (scm_random_exp, "random:exp", 0, 1, 0,
  597. (SCM state),
  598. "Return an inexact real in an exponential distribution with mean\n"
  599. "1. For an exponential distribution with mean u use (* u\n"
  600. "(random:exp)).")
  601. #define FUNC_NAME s_scm_random_exp
  602. {
  603. if (SCM_UNBNDP (state))
  604. state = SCM_VARIABLE_REF (scm_var_random_state);
  605. SCM_VALIDATE_RSTATE (1, state);
  606. return scm_from_double (scm_c_exp1 (SCM_RSTATE (state)));
  607. }
  608. #undef FUNC_NAME
  609. /* Return a new random-state seeded from the time, date, process ID, an
  610. address from a freshly allocated heap cell, an address from the local
  611. stack frame, and a high-resolution timer if available. This is only
  612. to be used as a last resort, when no better source of entropy is
  613. available. */
  614. static SCM
  615. random_state_of_last_resort (void)
  616. {
  617. SCM state;
  618. SCM time_of_day = scm_gettimeofday ();
  619. SCM sources = scm_list_n
  620. (scm_from_unsigned_integer (SCM_UNPACK (time_of_day)), /* heap addr */
  621. /* Avoid scm_getpid, since it depends on HAVE_POSIX. */
  622. scm_from_unsigned_integer (getpid ()), /* process ID */
  623. scm_get_internal_real_time (), /* high-resolution process timer */
  624. scm_from_unsigned_integer ((scm_t_bits) &time_of_day), /* stack addr */
  625. scm_car (time_of_day), /* seconds since midnight 1970-01-01 UTC */
  626. scm_cdr (time_of_day), /* microsecond component of the above clock */
  627. SCM_UNDEFINED);
  628. /* Concatenate the sources bitwise to form the seed */
  629. SCM seed = SCM_INUM0;
  630. while (scm_is_pair (sources))
  631. {
  632. seed = scm_logxor (seed, scm_ash (scm_car (sources),
  633. scm_integer_length (seed)));
  634. sources = scm_cdr (sources);
  635. }
  636. /* FIXME The following code belongs in `scm_seed_to_random_state',
  637. and here we should simply do:
  638. return scm_seed_to_random_state (seed);
  639. Unfortunately, `scm_seed_to_random_state' only preserves around 32
  640. bits of entropy from the provided seed. I don't know if it's okay
  641. to fix that in 2.0, so for now we have this workaround. */
  642. {
  643. int i, len;
  644. unsigned char *buf;
  645. len = scm_to_int (scm_ceiling_quotient (scm_integer_length (seed),
  646. SCM_I_MAKINUM (8)));
  647. buf = (unsigned char *) malloc (len);
  648. for (i = len-1; i >= 0; --i)
  649. {
  650. buf[i] = scm_to_int (scm_logand (seed, SCM_I_MAKINUM (255)));
  651. seed = scm_ash (seed, SCM_I_MAKINUM (-8));
  652. }
  653. state = make_rstate (scm_c_make_rstate ((char *) buf, len));
  654. free (buf);
  655. }
  656. return state;
  657. }
  658. /* Attempt to fill buffer with random bytes from /dev/urandom.
  659. Return 1 if successful, else return 0. */
  660. static int
  661. read_dev_urandom (unsigned char *buf, size_t len)
  662. {
  663. size_t res = 0;
  664. FILE *f = fopen ("/dev/urandom", "r");
  665. if (f)
  666. {
  667. res = fread(buf, 1, len, f);
  668. fclose (f);
  669. }
  670. return (res == len);
  671. }
  672. /* Fill a buffer with random bytes seeded from a platform-specific
  673. source of entropy. /dev/urandom is used if available. Note that
  674. this function provides no guarantees about the amount of entropy
  675. present in the returned bytes. */
  676. void
  677. scm_i_random_bytes_from_platform (unsigned char *buf, size_t len)
  678. {
  679. if (read_dev_urandom (buf, len))
  680. return;
  681. else /* FIXME: support other platform sources */
  682. {
  683. /* When all else fails, use this (rather weak) fallback */
  684. SCM random_state = random_state_of_last_resort ();
  685. int i;
  686. for (i = len-1; i >= 0; --i)
  687. buf[i] = scm_to_int (scm_random (SCM_I_MAKINUM (256), random_state));
  688. }
  689. }
  690. SCM_DEFINE (scm_random_state_from_platform, "random-state-from-platform", 0, 0, 0,
  691. (void),
  692. "Construct a new random state seeded from a platform-specific\n\
  693. source of entropy, appropriate for use in non-security-critical applications.")
  694. #define FUNC_NAME s_scm_random_state_from_platform
  695. {
  696. unsigned char buf[32];
  697. if (read_dev_urandom (buf, sizeof(buf)))
  698. return make_rstate (scm_c_make_rstate ((char *) buf, sizeof(buf)));
  699. else
  700. return random_state_of_last_resort ();
  701. }
  702. #undef FUNC_NAME
  703. void
  704. scm_init_random ()
  705. {
  706. int i, m;
  707. /* plug in default RNG */
  708. scm_t_rng rng =
  709. {
  710. sizeof (scm_t_i_rstate),
  711. scm_i_uniform32,
  712. scm_i_init_rstate,
  713. scm_i_copy_rstate,
  714. scm_i_rstate_from_datum,
  715. scm_i_rstate_to_datum
  716. };
  717. scm_the_rng = rng;
  718. scm_tc16_rstate = scm_make_smob_type ("random-state", 0);
  719. for (m = 1; m <= 0x100; m <<= 1)
  720. for (i = m >> 1; i < m; ++i)
  721. scm_masktab[i] = m - 1;
  722. #include "random.x"
  723. scm_add_feature ("random");
  724. }