random.c 23 KB

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