randn.js (2059B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var sqrt = require( '@stdlib/math/base/special/sqrt' ); 24 var ln = require( '@stdlib/math/base/special/ln' ); 25 var sin = require( '@stdlib/math/base/special/sin' ); 26 var cos = require( '@stdlib/math/base/special/cos' ); 27 var TWO_PI = require( '@stdlib/constants/float64/two-pi' ); 28 29 30 // MAIN // 31 32 /** 33 * Returns a function for generating standard normally distributed pseudorandom numbers using the Box-Muller algorithm. 34 * 35 * @private 36 * @param {PRNG} rand - PRNG which returns standard uniformly distributed numbers 37 * @returns {PRNG} PRNG 38 */ 39 function wrap( rand ) { 40 var flg; 41 var r; 42 43 // Flag indicating whether to generate new normal random variates or return a cached normal random variate: 44 flg = true; 45 46 return randn; 47 48 /** 49 * Generates a standard normally distributed pseudorandom number. 50 * 51 * @private 52 * @returns {number} pseudorandom number 53 * 54 * @example 55 * var r = randn(); 56 * // returns <number> 57 */ 58 function randn() { 59 var u1; 60 var u2; 61 var a; 62 var b; 63 if ( flg ) { 64 // Note: if `u1` is `0`, the natural log blows up, so we keep trying until we get a non-zero rand. Rarely should we need more than one iteration. 65 do { 66 u1 = rand(); 67 u2 = rand(); 68 } while ( 69 u1 === 0.0 70 ); 71 a = sqrt( -2.0 * ln(u1) ); 72 b = TWO_PI * u2; 73 r = a * cos( b ); // cache for next call 74 flg = false; 75 return a * sin( b ); 76 } 77 flg = true; 78 return r; 79 } 80 } 81 82 83 // EXPORTS // 84 85 module.exports = wrap;