GNU Octave 7.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
randmtzig.cc
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////
2//
3// Copyright (C) 2006-2022 The Octave Project Developers
4//
5// See the file COPYRIGHT.md in the top-level directory of this
6// distribution or <https://octave.org/copyright/>.
7//
8// This file is part of Octave.
9//
10// Octave is free software: you can redistribute it and/or modify it
11// under the terms of the GNU General Public License as published by
12// the Free Software Foundation, either version 3 of the License, or
13// (at your option) any later version.
14//
15// Octave is distributed in the hope that it will be useful, but
16// WITHOUT ANY WARRANTY; without even the implied warranty of
17// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18// GNU General Public License for more details.
19//
20// You should have received a copy of the GNU General Public License
21// along with Octave; see the file COPYING. If not, see
22// <https://www.gnu.org/licenses/>.
23//
24////////////////////////////////////////////////////////////////////////
25
26/*
27 A C-program for MT19937, with initialization improved 2002/2/10.
28 Coded by Takuji Nishimura and Makoto Matsumoto.
29 This is a faster version by taking Shawn Cokus's optimization,
30 Matthe Bellew's simplification, Isaku Wada's real version.
31 David Bateman added normal and exponential distributions following
32 Marsaglia and Tang's Ziggurat algorithm.
33
34 Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
35 Copyright (C) 2004, David Bateman
36 All rights reserved.
37
38 Redistribution and use in source and binary forms, with or without
39 modification, are permitted provided that the following conditions
40 are met:
41
42 1. Redistributions of source code must retain the above copyright
43 notice, this list of conditions and the following disclaimer.
44
45 2. Redistributions in binary form must reproduce the above copyright
46 notice, this list of conditions and the following disclaimer in the
47 documentation and/or other materials provided with the distribution.
48
49 3. The names of its contributors may not be used to endorse or promote
50 products derived from this software without specific prior written
51 permission.
52
53 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
54 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
55 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
56 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
57 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64
65
66 Any feedback is very welcome.
67 http://www.math.keio.ac.jp/matumoto/emt.html
68 email: matumoto@math.keio.ac.jp
69
70 * 2004-01-19 Paul Kienzle
71 * * comment out main
72 * add init_by_entropy, get_state, set_state
73 * * converted to allow compiling by C++ compiler
74 *
75 * 2004-01-25 David Bateman
76 * * Add Marsaglia and Tsang Ziggurat code
77 *
78 * 2004-07-13 Paul Kienzle
79 * * make into an independent library with some docs.
80 * * introduce new main and test code.
81 *
82 * 2004-07-28 Paul Kienzle & David Bateman
83 * * add -DALLBITS flag for 32 vs. 53 bits of randomness in mantissa
84 * * make the naming scheme more uniform
85 * * add -DHAVE_X86 for faster support of 53 bit mantissa on x86 arch.
86 *
87 * 2005-02-23 Paul Kienzle
88 * * fix -DHAVE_X86_32 flag and add -DUSE_X86_32=0|1 for explicit control
89 *
90 * 2006-04-01 David Bateman
91 * * convert for use in octave, declaring static functions only used
92 * here and adding oct_ to functions visible externally
93 * * inverse sense of ALLBITS
94 *
95 * 2012-05-18 David Bateman
96 * * Remove randu64 and ALLBIT option
97 * * Add the single precision generators
98 */
99
100/*
101 === Build instructions ===
102
103 Compile with -DHAVE_GETTIMEOFDAY if the gettimeofday function is
104 available. This is not necessary if your architecture has
105 /dev/urandom defined.
106
107 Uses implicit -Di386 or explicit -DHAVE_X86_32 to determine if CPU=x86.
108 You can force X86 behavior with -DUSE_X86_32=1, or suppress it with
109 -DUSE_X86_32=0. You should also consider -march=i686 or similar for
110 extra performance. Check whether -DUSE_X86_32=0 is faster on 64-bit
111 x86 architectures.
112
113 If you want to replace the Mersenne Twister with another
114 generator then redefine randi32 appropriately.
115
116 === Usage instructions ===
117 Before using any of the generators, initialize the state with one of
118 the init_mersenne_twister functions.
119
120 All generators share the same state vector.
121
122 === Mersenne Twister ===
123 random initial state:
124 void init_mersenne_twister (void)
125
126 // 32-bit initial state:
127 void init_mersenne_twister (uint32_t s)
128
129 // m*32-bit initial state:
130 void init_mersenne_twister (uint32_t k[],int m)
131
132 // saves state in array:
133 void get_mersenne_twister_state (uint32_t save[MT_N+1])
134
135 // restores state from array
136 void set_mersenne_twister_state (uint32_t save[MT_N+1])
137
138 static uint32_t randmt (void) returns 32-bit unsigned int
139
140 === inline generators ===
141 static uint32_t randi32 (void) returns 32-bit unsigned int
142 static uint64_t randi53 (void) returns 53-bit unsigned int
143 static uint64_t randi54 (void) returns 54-bit unsigned int
144 static float randu24 (void) returns 24-bit uniform in (0,1)
145 static double randu53 (void) returns 53-bit uniform in (0,1)
146
147 double rand_uniform (void) returns M-bit uniform in (0,1)
148 double rand_normal (void) returns M-bit standard normal
149 double rand_exponential (void) returns N-bit standard exponential
150
151 === Array generators ===
152 void rand_uniform (octave_idx_type, double [])
153 void rand_normal (octave_idx_type, double [])
154 void rand_exponential (octave_idx_type, double [])
155*/
156
157#if defined (HAVE_CONFIG_H)
158# include "config.h"
159#endif
160
161#include <cmath>
162#include <cstdio>
163
164#include <algorithm>
165#include <random>
166
167#include "oct-syscalls.h"
168#include "oct-time.h"
169#include "randmtzig.h"
170
171/* FIXME: may want to suppress X86 if sizeof(long) > 4 */
172#if ! defined (USE_X86_32)
173# if defined (i386) || defined (HAVE_X86_32)
174# define USE_X86_32 1
175# else
176# define USE_X86_32 0
177# endif
178#endif
179
180namespace octave
181{
182 /* ===== Mersenne Twister 32-bit generator ===== */
183
184#define MT_M 397
185#define MATRIX_A 0x9908b0dfUL /* constant vector a */
186#define UMASK 0x80000000UL /* most significant w-r bits */
187#define LMASK 0x7fffffffUL /* least significant r bits */
188#define MIXBITS(u,v) ( ((u) & UMASK) | ((v) & LMASK) )
189#define TWIST(u,v) ((MIXBITS(u,v) >> 1) ^ ((v)&1UL ? MATRIX_A : 0UL))
190
191 static uint32_t *next;
192 static uint32_t state[MT_N]; /* the array for the state vector */
193 static int left = 1;
194 static int initf = 0;
195 static int initt = 1;
196 static int inittf = 1;
197
198 /* initializes state[MT_N] with a seed */
199 void init_mersenne_twister (const uint32_t s)
200 {
201 int j;
202 state[0] = s & 0xffffffffUL;
203 for (j = 1; j < MT_N; j++)
204 {
205 state[j] = (1812433253UL * (state[j-1] ^ (state[j-1] >> 30)) + j);
206 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
207 /* In the previous versions, MSBs of the seed affect */
208 /* only MSBs of the array state[]. */
209 /* 2002/01/09 modified by Makoto Matsumoto */
210 state[j] &= 0xffffffffUL; /* for >32 bit machines */
211 }
212 left = 1;
213 initf = 1;
214 }
215
216 /* initialize by an array with array-length */
217 /* init_key is the array for initializing keys */
218 /* key_length is its length */
219 void init_mersenne_twister (const uint32_t *init_key, const int key_length)
220 {
221 int i, j, k;
222 init_mersenne_twister (19650218UL);
223 i = 1;
224 j = 0;
225 k = (MT_N > key_length ? MT_N : key_length);
226 for (; k; k--)
227 {
228 state[i] = (state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1664525UL))
229 + init_key[j] + j; /* non linear */
230 state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
231 i++;
232 j++;
233 if (i >= MT_N)
234 {
235 state[0] = state[MT_N-1];
236 i = 1;
237 }
238 if (j >= key_length)
239 j = 0;
240 }
241 for (k = MT_N - 1; k; k--)
242 {
243 state[i] = (state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL))
244 - i; /* non linear */
245 state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
246 i++;
247 if (i >= MT_N)
248 {
249 state[0] = state[MT_N-1];
250 i = 1;
251 }
252 }
253
254 state[0] = 0x80000000UL; /* MSB is 1; assuring nonzero initial array */
255 left = 1;
256 initf = 1;
257 }
258
260 {
261 uint32_t entropy[MT_N];
262 int n = 0;
263
264 // Gather some entropy from various sources
265
266 sys::time now;
267
268 // Current time in seconds
269 if (n < MT_N)
270 entropy[n++] = now.unix_time ();
271
272 // CPU time used (usec)
273 if (n < MT_N)
274 entropy[n++] = clock ();
275
276 // Fractional part of current time
277 if (n < MT_N)
278 entropy[n++] = now.usec ();
279
280 // Include the PID to make sure that several processes reaching here at the
281 // same time use different random numbers.
282 if (n < MT_N)
283 entropy[n++] = sys::getpid ();
284
285 if (n < MT_N)
286 {
287 try
288 {
289 // The standard doesn't *guarantee* that random_device provides
290 // non-deterministic random numbers. So add entropy from this
291 // source last to make sure we gathered at least some entropy from
292 // the earlier sources.
293 std::random_device rd;
294 std::uniform_int_distribution<uint32_t> dist;
295 // Add 1024 bit of "true" entropy
296 int n_max = std::min (n + 32, MT_N);
297 while (n < n_max)
298 entropy[n++] = dist (rd);
299 }
300 catch (const std::exception&)
301 {
302 // Just ignore any exception and skip that source of entropy.
303 }
304 }
305
306 // Send all the entropy into the initial state vector
307 init_mersenne_twister (entropy, n);
308 }
309
310 void set_mersenne_twister_state (const uint32_t *save)
311 {
312 std::copy_n (save, MT_N, state);
313 left = save[MT_N];
314 next = state + (MT_N - left + 1);
315 }
316
317 void get_mersenne_twister_state (uint32_t *save)
318 {
319 std::copy_n (state, MT_N, save);
320 save[MT_N] = left;
321 }
322
323 static void next_state (void)
324 {
325 uint32_t *p = state;
326 int j;
327
328 /* if init_by_int() has not been called, */
329 /* a default initial seed is used */
330 /* if (initf==0) init_by_int(5489UL); */
331 /* Or better yet, a random seed! */
332 if (initf == 0)
334
335 left = MT_N;
336 next = state;
337
338 for (j = MT_N - MT_M + 1; --j; p++)
339 *p = p[MT_M] ^ TWIST(p[0], p[1]);
340
341 for (j = MT_M; --j; p++)
342 *p = p[MT_M-MT_N] ^ TWIST(p[0], p[1]);
343
344 *p = p[MT_M-MT_N] ^ TWIST(p[0], state[0]);
345 }
346
347 /* generates a random number on [0,0xffffffff]-interval */
348 static uint32_t randmt (void)
349 {
350 uint32_t y;
351
352 if (--left == 0)
353 next_state ();
354 y = *next++;
355
356 /* Tempering */
357 y ^= (y >> 11);
358 y ^= (y << 7) & 0x9d2c5680UL;
359 y ^= (y << 15) & 0xefc60000UL;
360 return (y ^ (y >> 18));
361 }
362
363 /* ===== Uniform generators ===== */
364
365 /* Select which 32 bit generator to use */
366#define randi32 randmt
367
368 static uint64_t randi53 (void)
369 {
370 const uint32_t lo = randi32 ();
371 const uint32_t hi = randi32 () & 0x1FFFFF;
372#if defined (HAVE_X86_32)
373 uint64_t u;
374 uint32_t *p = (uint32_t *)&u;
375 p[0] = lo;
376 p[1] = hi;
377 return u;
378#else
379 return ((static_cast<uint64_t> (hi) << 32) | lo);
380#endif
381 }
382
383 static uint64_t randi54 (void)
384 {
385 const uint32_t lo = randi32 ();
386 const uint32_t hi = randi32 () & 0x3FFFFF;
387#if defined (HAVE_X86_32)
388 uint64_t u;
389 uint32_t *p = static_cast<uint32_t *> (&u);
390 p[0] = lo;
391 p[1] = hi;
392 return u;
393#else
394 return ((static_cast<uint64_t> (hi) << 32) | lo);
395#endif
396 }
397
398 /* generates a random number on (0,1)-real-interval */
399 static float randu24 (void)
400 {
401 uint32_t i;
402
403 do
404 {
405 i = randi32 () & static_cast<uint32_t> (0xFFFFFF);
406 }
407 while (i == 0);
408
409 return i * (1.0f / 16777216.0f);
410 }
411
412 /* generates a random number on (0,1) with 53-bit resolution */
413 static double randu53 (void)
414 {
415 int32_t a, b;
416
417 do
418 {
419 a = randi32 () >> 5;
420 b = randi32 () >> 6;
421 }
422 while (a == 0 && b == 0);
423
424 return (a*67108864.0 + b) * (1.0/9007199254740992.0);
425 }
426
427 /* Determine mantissa for uniform doubles */
428 template <>
431 {
432 return randu53 ();
433 }
434
435 /* Determine mantissa for uniform floats */
436 template <>
439 {
440 return randu24 ();
441 }
442
443 /* ===== Ziggurat normal and exponential generators ===== */
444
445#define ZIGGURAT_TABLE_SIZE 256
446
447#define ZIGGURAT_NOR_R 3.6541528853610088
448#define ZIGGURAT_NOR_INV_R 0.27366123732975828
449#define NOR_SECTION_AREA 0.00492867323399
450
451#define ZIGGURAT_EXP_R 7.69711747013104972
452#define ZIGGURAT_EXP_INV_R 0.129918765548341586
453#define EXP_SECTION_AREA 0.0039496598225815571993
454
455#define ZIGINT uint64_t
456#define EMANTISSA 9007199254740992.0 /* 53 bit mantissa */
457#define ERANDI randi53() /* 53 bits for mantissa */
458#define NMANTISSA EMANTISSA
459#define NRANDI randi54() /* 53 bits for mantissa + 1 bit sign */
460#define RANDU randu53()
461
466
467 /*
468 This code is based on the paper Marsaglia and Tsang, "The ziggurat method
469 for generating random variables", Journ. Statistical Software. Code was
470 presented in this paper for a Ziggurat of 127 levels and using a 32 bit
471 integer random number generator. This version of the code, uses the
472 Mersenne Twister as the integer generator and uses 256 levels in the
473 Ziggurat. This has several advantages.
474
475 1) As Marsaglia and Tsang themselves states, the more levels the few
476 times the expensive tail algorithm must be called
477 2) The cycle time of the generator is determined by the integer
478 generator, thus the use of a Mersenne Twister for the core random
479 generator makes this cycle extremely long.
480 3) The license on the original code was unclear, thus rewriting the code
481 from the article means we are free of copyright issues.
482 4) Compile flag for full 53-bit random mantissa.
483
484 It should be stated that the authors made my life easier, by the fact that
485 the algorithm developed in the text of the article is for a 256 level
486 ziggurat, even if the code itself isn't...
487
488 One modification to the algorithm developed in the article, is that it is
489 assumed that 0 <= x < Inf, and "unsigned long"s are used, thus resulting in
490 terms like 2^32 in the code. As the normal distribution is defined between
491 -Inf < x < Inf, we effectively only have 31 bit integers plus a sign. Thus
492 in Marsaglia and Tsang, terms like 2^32 become 2^31. We use NMANTISSA for
493 this term. The exponential distribution is one sided so we use the
494 full 32 bits. We use EMANTISSA for this term.
495
496 It appears that I'm slightly slower than the code in the article, this
497 is partially due to a better generator of random integers than they
498 use. But might also be that the case of rapid return was optimized by
499 inlining the relevant code with a #define. As the basic Mersenne
500 Twister is only 25% faster than this code I suspect that the main
501 reason is just the use of the Mersenne Twister and not the inlining,
502 so I'm not going to try and optimize further.
503 */
504
506 {
507 int i;
508 double x, x1;
509
510 /* Ziggurat tables for the normal distribution */
511 x1 = ZIGGURAT_NOR_R;
512 wi[255] = x1 / NMANTISSA;
513 fi[255] = exp (-0.5 * x1 * x1);
514
515 /* Index zero is special for tail strip, where Marsaglia and Tsang
516 * defines this as
517 * k_0 = 2^31 * r * f(r) / v, w_0 = 0.5^31 * v / f(r), f_0 = 1,
518 * where v is the area of each strip of the ziggurat.
519 */
520 ki[0] = static_cast<ZIGINT> (x1 * fi[255] / NOR_SECTION_AREA * NMANTISSA);
521 wi[0] = NOR_SECTION_AREA / fi[255] / NMANTISSA;
522 fi[0] = 1.;
523
524 for (i = 254; i > 0; i--)
525 {
526 /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
527 * need inverse operator of y = exp(-0.5*x*x) -> x = sqrt(-2*ln(y))
528 */
529 x = std::sqrt (-2. * std::log (NOR_SECTION_AREA / x1 + fi[i+1]));
530 ki[i+1] = static_cast<ZIGINT> (x / x1 * NMANTISSA);
531 wi[i] = x / NMANTISSA;
532 fi[i] = exp (-0.5 * x * x);
533 x1 = x;
534 }
535
536 ki[1] = 0;
537
538 /* Zigurrat tables for the exponential distribution */
539 x1 = ZIGGURAT_EXP_R;
540 we[255] = x1 / EMANTISSA;
541 fe[255] = exp (-x1);
542
543 /* Index zero is special for tail strip, where Marsaglia and Tsang
544 * defines this as
545 * k_0 = 2^32 * r * f(r) / v, w_0 = 0.5^32 * v / f(r), f_0 = 1,
546 * where v is the area of each strip of the ziggurat.
547 */
548 ke[0] = static_cast<ZIGINT> (x1 * fe[255] / EXP_SECTION_AREA * EMANTISSA);
549 we[0] = EXP_SECTION_AREA / fe[255] / EMANTISSA;
550 fe[0] = 1.;
551
552 for (i = 254; i > 0; i--)
553 {
554 /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
555 * need inverse operator of y = exp(-x) -> x = -ln(y)
556 */
557 x = - std::log (EXP_SECTION_AREA / x1 + fe[i+1]);
558 ke[i+1] = static_cast<ZIGINT> (x / x1 * EMANTISSA);
559 we[i] = x / EMANTISSA;
560 fe[i] = exp (-x);
561 x1 = x;
562 }
563 ke[1] = 0;
564
565 initt = 0;
566 }
567
568 /*
569 * Here is the guts of the algorithm. As Marsaglia and Tsang state the
570 * algorithm in their paper
571 *
572 * 1) Calculate a random signed integer j and let i be the index
573 * provided by the rightmost 8-bits of j
574 * 2) Set x = j * w_i. If j < k_i return x
575 * 3) If i = 0, then return x from the tail
576 * 4) If [f(x_{i-1}) - f(x_i)] * U < f(x) - f(x_i), return x
577 * 5) goto step 1
578 *
579 * Where f is the functional form of the distribution, which for a normal
580 * distribution is exp(-0.5*x*x)
581 */
582
583
584 template <> OCTAVE_API double rand_normal<double> (void)
585 {
586 if (initt)
588
589 while (1)
590 {
591 /* The following code is specialized for 32-bit mantissa.
592 * Compared to the arbitrary mantissa code, there is a performance
593 * gain for 32-bits: PPC: 2%, MIPS: 8%, x86: 40%
594 * There is a bigger performance gain compared to using a full
595 * 53-bit mantissa: PPC: 60%, MIPS: 65%, x86: 240%
596 * Of course, different compilers and operating systems may
597 * have something to do with this.
598 */
599# if defined (HAVE_X86_32)
600 /* 53-bit mantissa, 1-bit sign, x86 32-bit architecture */
601 double x;
602 int si, idx;
603 uint32_t lo, hi;
604 int64_t rabs;
605 uint32_t *p = (uint32_t *)&rabs;
606 lo = randi32 ();
607 idx = lo & 0xFF;
608 hi = randi32 ();
609 si = hi & UMASK;
610 p[0] = lo;
611 p[1] = hi & 0x1FFFFF;
612 x = ( si ? -rabs : rabs ) * wi[idx];
613# else
614 /* arbitrary mantissa (selected by NRANDI, with 1 bit for sign) */
615 const uint64_t r = NRANDI;
616 const int64_t rabs = r >> 1;
617 const int idx = static_cast<int> (rabs & 0xFF);
618 const double x = ( (r & 1) ? -rabs : rabs) * wi[idx];
619# endif
620 if (rabs < static_cast<int64_t> (ki[idx]))
621 return x; /* 99.3% of the time we return here 1st try */
622 else if (idx == 0)
623 {
624 /* As stated in Marsaglia and Tsang
625 *
626 * For the normal tail, the method of Marsaglia[5] provides:
627 * generate x = -ln(U_1)/r, y = -ln(U_2), until y+y > x*x,
628 * then return r+x. Except that r+x is always in the positive
629 * tail!!!! Any thing random might be used to determine the
630 * sign, but as we already have r we might as well use it
631 *
632 * [PAK] but not the bottom 8 bits, since they are all 0 here!
633 */
634 double xx, yy;
635 do
636 {
637 xx = - ZIGGURAT_NOR_INV_R * std::log (RANDU);
638 yy = - std::log (RANDU);
639 }
640 while ( yy+yy <= xx*xx);
641 return ((rabs & 0x100) ? -ZIGGURAT_NOR_R-xx : ZIGGURAT_NOR_R+xx);
642 }
643 else if ((fi[idx-1] - fi[idx]) * RANDU + fi[idx] < exp (-0.5*x*x))
644 return x;
645 }
646 }
647
648 template <> OCTAVE_API double rand_exponential<double> (void)
649 {
650 if (initt)
652
653 while (1)
654 {
655 ZIGINT ri = ERANDI;
656 const int idx = static_cast<int> (ri & 0xFF);
657 const double x = ri * we[idx];
658 if (ri < ke[idx])
659 return x; /* 98.9% of the time we return here 1st try */
660 else if (idx == 0)
661 {
662 /* As stated in Marsaglia and Tsang
663 *
664 * For the exponential tail, the method of Marsaglia[5] provides:
665 * x = r - ln(U);
666 */
667 return ZIGGURAT_EXP_R - std::log (RANDU);
668 }
669 else if ((fe[idx-1] - fe[idx]) * RANDU + fe[idx] < exp (-x))
670 return x;
671 }
672 }
673
674 template <> OCTAVE_API void rand_uniform<double> (octave_idx_type n, double *p)
675 {
676 std::generate_n (p, n, [](void) { return rand_uniform<double> (); });
677 }
678
679 template <> OCTAVE_API void rand_normal (octave_idx_type n, double *p)
680 {
681 std::generate_n (p, n, [](void) { return rand_normal<double> (); });
682 }
683
684 template <> OCTAVE_API void rand_exponential (octave_idx_type n, double *p)
685 {
686 std::generate_n (p, n, [](void) { return rand_exponential<double> (); });
687 }
688
689#undef ZIGINT
690#undef EMANTISSA
691#undef ERANDI
692#undef NMANTISSA
693#undef NRANDI
694#undef RANDU
695
696#define ZIGINT uint32_t
697#define EMANTISSA 4294967296.0 /* 32 bit mantissa */
698#define ERANDI randi32() /* 32 bits for mantissa */
699#define NMANTISSA 2147483648.0 /* 31 bit mantissa */
700#define NRANDI randi32() /* 31 bits for mantissa + 1 bit sign */
701#define RANDU randu24()
702
707
709 {
710 int i;
711 float x, x1;
712
713 /* Ziggurat tables for the normal distribution */
714 x1 = ZIGGURAT_NOR_R;
715 fwi[255] = x1 / NMANTISSA;
716 ffi[255] = exp (-0.5 * x1 * x1);
717
718 /* Index zero is special for tail strip, where Marsaglia and Tsang
719 * defines this as
720 * k_0 = 2^31 * r * f(r) / v, w_0 = 0.5^31 * v / f(r), f_0 = 1,
721 * where v is the area of each strip of the ziggurat.
722 */
723 fki[0] = static_cast<ZIGINT> (x1 * ffi[255] / NOR_SECTION_AREA * NMANTISSA);
724 fwi[0] = NOR_SECTION_AREA / ffi[255] / NMANTISSA;
725 ffi[0] = 1.;
726
727 for (i = 254; i > 0; i--)
728 {
729 /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
730 * need inverse operator of y = exp(-0.5*x*x) -> x = sqrt(-2*ln(y))
731 */
732 x = std::sqrt (-2. * std::log (NOR_SECTION_AREA / x1 + ffi[i+1]));
733 fki[i+1] = static_cast<ZIGINT> (x / x1 * NMANTISSA);
734 fwi[i] = x / NMANTISSA;
735 ffi[i] = exp (-0.5 * x * x);
736 x1 = x;
737 }
738
739 fki[1] = 0;
740
741 /* Zigurrat tables for the exponential distribution */
742 x1 = ZIGGURAT_EXP_R;
743 fwe[255] = x1 / EMANTISSA;
744 ffe[255] = exp (-x1);
745
746 /* Index zero is special for tail strip, where Marsaglia and Tsang
747 * defines this as
748 * k_0 = 2^32 * r * f(r) / v, w_0 = 0.5^32 * v / f(r), f_0 = 1,
749 * where v is the area of each strip of the ziggurat.
750 */
751 fke[0] = static_cast<ZIGINT> (x1 * ffe[255] / EXP_SECTION_AREA * EMANTISSA);
752 fwe[0] = EXP_SECTION_AREA / ffe[255] / EMANTISSA;
753 ffe[0] = 1.;
754
755 for (i = 254; i > 0; i--)
756 {
757 /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
758 * need inverse operator of y = exp(-x) -> x = -ln(y)
759 */
760 x = - std::log (EXP_SECTION_AREA / x1 + ffe[i+1]);
761 fke[i+1] = static_cast<ZIGINT> (x / x1 * EMANTISSA);
762 fwe[i] = x / EMANTISSA;
763 ffe[i] = exp (-x);
764 x1 = x;
765 }
766 fke[1] = 0;
767
768 inittf = 0;
769 }
770
771 /*
772 * Here is the guts of the algorithm. As Marsaglia and Tsang state the
773 * algorithm in their paper
774 *
775 * 1) Calculate a random signed integer j and let i be the index
776 * provided by the rightmost 8-bits of j
777 * 2) Set x = j * w_i. If j < k_i return x
778 * 3) If i = 0, then return x from the tail
779 * 4) If [f(x_{i-1}) - f(x_i)] * U < f(x) - f(x_i), return x
780 * 5) goto step 1
781 *
782 * Where f is the functional form of the distribution, which for a normal
783 * distribution is exp(-0.5*x*x)
784 */
785
786 template <> OCTAVE_API float rand_normal<float> (void)
787 {
788 if (inittf)
790
791 while (1)
792 {
793 /* 32-bit mantissa */
794 const uint32_t r = randi32 ();
795 const uint32_t rabs = r & LMASK;
796 const int idx = static_cast<int> (r & 0xFF);
797 const float x = static_cast<int32_t> (r) * fwi[idx];
798 if (rabs < fki[idx])
799 return x; /* 99.3% of the time we return here 1st try */
800 else if (idx == 0)
801 {
802 /* As stated in Marsaglia and Tsang
803 *
804 * For the normal tail, the method of Marsaglia[5] provides:
805 * generate x = -ln(U_1)/r, y = -ln(U_2), until y+y > x*x,
806 * then return r+x. Except that r+x is always in the positive
807 * tail!!!! Any thing random might be used to determine the
808 * sign, but as we already have r we might as well use it
809 *
810 * [PAK] but not the bottom 8 bits, since they are all 0 here!
811 */
812 float xx, yy;
813 do
814 {
815 xx = - ZIGGURAT_NOR_INV_R * std::log (RANDU);
816 yy = - std::log (RANDU);
817 }
818 while ( yy+yy <= xx*xx);
819 return ((rabs & 0x100) ? -ZIGGURAT_NOR_R-xx : ZIGGURAT_NOR_R+xx);
820 }
821 else if ((ffi[idx-1] - ffi[idx]) * RANDU + ffi[idx] < exp (-0.5*x*x))
822 return x;
823 }
824 }
825
826 template <> OCTAVE_API float rand_exponential<float> (void)
827 {
828 if (inittf)
830
831 while (1)
832 {
833 ZIGINT ri = ERANDI;
834 const int idx = static_cast<int> (ri & 0xFF);
835 const float x = ri * fwe[idx];
836 if (ri < fke[idx])
837 return x; /* 98.9% of the time we return here 1st try */
838 else if (idx == 0)
839 {
840 /* As stated in Marsaglia and Tsang
841 *
842 * For the exponential tail, the method of Marsaglia[5] provides:
843 * x = r - ln(U);
844 */
845 return ZIGGURAT_EXP_R - std::log (RANDU);
846 }
847 else if ((ffe[idx-1] - ffe[idx]) * RANDU + ffe[idx] < exp (-x))
848 return x;
849 }
850 }
851
852 template <> OCTAVE_API void rand_uniform (octave_idx_type n, float *p)
853 {
854 std::generate_n (p, n, [](void) { return rand_uniform<float> (); });
855 }
856
857 template <> OCTAVE_API void rand_normal (octave_idx_type n, float *p)
858 {
859 std::generate_n (p, n, [](void) { return rand_normal<float> (); });
860 }
861
862 template <> OCTAVE_API void rand_exponential (octave_idx_type n, float *p)
863 {
864 std::generate_n (p, n, [](void) { return rand_exponential<float> (); });
865 }
866}
867
charNDArray min(char d, const charNDArray &m)
Definition: chNDArray.cc:207
OCTAVE_TIME_T unix_time(void) const
Definition: oct-time.h:110
long usec(void) const
Definition: oct-time.h:112
F77_RET_T const F77_DBLE * x
#define OCTAVE_API
Definition: main.in.cc:55
pid_t getpid(void)
static uint64_t randi53(void)
Definition: randmtzig.cc:368
static float randu24(void)
Definition: randmtzig.cc:399
static uint32_t state[624]
Definition: randmtzig.cc:192
OCTAVE_API float rand_uniform< float >(void)
Definition: randmtzig.cc:438
static double we[256]
Definition: randmtzig.cc:465
void get_mersenne_twister_state(uint32_t *save)
Definition: randmtzig.cc:317
static uint32_t randmt(void)
Definition: randmtzig.cc:348
static uint64_t randi54(void)
Definition: randmtzig.cc:383
static float fwi[256]
Definition: randmtzig.cc:704
static float ffi[256]
Definition: randmtzig.cc:704
static int inittf
Definition: randmtzig.cc:196
static void create_ziggurat_float_tables(void)
Definition: randmtzig.cc:708
static uint32_t fke[256]
Definition: randmtzig.cc:705
OCTAVE_API void rand_exponential(octave_idx_type n, double *p)
Definition: randmtzig.cc:684
static uint64_t ki[256]
Definition: randmtzig.cc:462
static uint32_t * next
Definition: randmtzig.cc:191
static int left
Definition: randmtzig.cc:193
static int initf
Definition: randmtzig.cc:194
static double wi[256]
Definition: randmtzig.cc:463
OCTAVE_API double rand_uniform< double >(void)
Definition: randmtzig.cc:430
static uint32_t fki[256]
Definition: randmtzig.cc:703
static float ffe[256]
Definition: randmtzig.cc:706
void init_mersenne_twister(const uint32_t s)
Definition: randmtzig.cc:199
static void next_state(void)
Definition: randmtzig.cc:323
static double fe[256]
Definition: randmtzig.cc:465
OCTAVE_API double rand_normal< double >(void)
Definition: randmtzig.cc:584
void create_ziggurat_tables(void)
Definition: randmtzig.cc:505
static uint64_t ke[256]
Definition: randmtzig.cc:464
OCTAVE_API float rand_normal< float >(void)
Definition: randmtzig.cc:786
OCTAVE_API void rand_normal(octave_idx_type n, double *p)
Definition: randmtzig.cc:679
void set_mersenne_twister_state(const uint32_t *save)
Definition: randmtzig.cc:310
static int initt
Definition: randmtzig.cc:195
OCTAVE_API void rand_uniform(octave_idx_type n, float *p)
Definition: randmtzig.cc:852
static float fwe[256]
Definition: randmtzig.cc:706
static double fi[256]
Definition: randmtzig.cc:463
OCTAVE_API double rand_exponential< double >(void)
Definition: randmtzig.cc:648
OCTAVE_API float rand_exponential< float >(void)
Definition: randmtzig.cc:826
static double randu53(void)
Definition: randmtzig.cc:413
#define TWIST(u, v)
Definition: randmtzig.cc:189
#define ZIGGURAT_EXP_R
Definition: randmtzig.cc:451
#define EMANTISSA
Definition: randmtzig.cc:697
#define ZIGGURAT_TABLE_SIZE
Definition: randmtzig.cc:445
#define randi32
Definition: randmtzig.cc:366
#define RANDU
Definition: randmtzig.cc:701
#define ZIGINT
Definition: randmtzig.cc:696
#define LMASK
Definition: randmtzig.cc:187
#define NRANDI
Definition: randmtzig.cc:700
#define ERANDI
Definition: randmtzig.cc:698
#define NOR_SECTION_AREA
Definition: randmtzig.cc:449
#define ZIGGURAT_NOR_R
Definition: randmtzig.cc:447
#define ZIGGURAT_NOR_INV_R
Definition: randmtzig.cc:448
#define UMASK
Definition: randmtzig.cc:186
#define NMANTISSA
Definition: randmtzig.cc:699
#define MT_M
Definition: randmtzig.cc:184
#define EXP_SECTION_AREA
Definition: randmtzig.cc:453
#define MT_N
Definition: randmtzig.h:72