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