random.c 24 KB

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