gamma.js (1584B)
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 ln = require( '@stdlib/math/base/special/ln' ); 24 25 26 // MAIN // 27 28 /** 29 * Returns a pseudorandom number drawn from a gamma distribution. 30 * 31 * @private 32 * @param {PRNG} randu - PRNG for uniformly distributed numbers 33 * @param {PRNG} randn - PRNG for standard normally distributed numbers 34 * @param {PositiveNumber} beta - rate parameter 35 * @param {PositiveNumber} d - `alpha + 2/3` or `alpha - 1/3` 36 * @param {PositiveNumber} c - `1.0 / sqrt( 9.0*d )` 37 * @returns {PositiveNumber} pseudorandom number 38 */ 39 function gamma( randu, randn, beta, d, c ) { 40 var flg; 41 var x2; 42 var v0; 43 var v1; 44 var x; 45 var u; 46 var v; 47 48 flg = true; 49 while ( flg ) { 50 do { 51 x = randn(); 52 v = 1.0 + (c*x); 53 } while ( v <= 0.0 ); 54 v *= v * v; 55 x2 = x * x; 56 v0 = 1.0 - (0.331*x2*x2); 57 v1 = (0.5*x2) + (d*( 1.0-v+ln(v) )); 58 u = randu(); 59 if ( u < v0 || ln( u ) < v1 ) { 60 flg = false; 61 } 62 } 63 return (1.0/beta) * d * v; 64 } 65 66 67 // EXPORTS // 68 69 module.exports = gamma;