time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

sample2.js (1698B)


      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 pow = require( '@stdlib/math/base/special/pow' );
     24 var ln = require( '@stdlib/math/base/special/ln' );
     25 
     26 
     27 // MAIN //
     28 
     29 /**
     30 * Handles case where both `alpha` and `beta` are greater than `1.0`.
     31 *
     32 * @private
     33 * @param {PRNG} randu - PRNG for uniformly distributed numbers
     34 * @param {PRNG} randn - PRNG for normally distributed numbers
     35 * @param {PositiveNumber} alpha - first shape parameter
     36 * @param {PositiveNumber} beta - second shape parameter
     37 * @returns {Probability} pseudorandom number
     38 */
     39 function sample( randu, randn, alpha, beta ) {
     40 	var sigma;
     41 	var flg;
     42 	var mu;
     43 	var A;
     44 	var B;
     45 	var C;
     46 	var L;
     47 	var s;
     48 	var u;
     49 	var x;
     50 	var y;
     51 
     52 	A = alpha - 1.0;
     53 	B = beta - 1.0;
     54 	C = A + B;
     55 	L = C * ln( C );
     56 	mu = A / C;
     57 	sigma = 0.5 / pow( C, 0.5 );
     58 
     59 	flg = true;
     60 	while ( flg === true ) {
     61 		s = randn();
     62 		x = mu + (s*sigma);
     63 		if ( x >= 0.0 && x <= 1.0 ) {
     64 			u = randu();
     65 			y = A * ln( x/A );
     66 			y += B * ln((1.0-x) / B);
     67 			y += L + (0.5*s*s);
     68 			if ( y >= ln( u ) ) {
     69 				flg = false;
     70 			}
     71 		}
     72 	}
     73 	return x;
     74 }
     75 
     76 
     77 // EXPORTS //
     78 
     79 module.exports = sample;