random.c 23 KB

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