time-to-botec

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

sample1.js (1737B)


      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 `alpha` and `beta` are equal and greater than `1.5`.
     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 * @returns {Probability} pseudorandom number
     37 */
     38 function sample( randu, randn, alpha ) {
     39 	var flg;
     40 	var s4;
     41 	var A;
     42 	var s;
     43 	var t;
     44 	var u;
     45 	var x;
     46 	var y;
     47 
     48 	A = alpha - 1.0;
     49 	t = pow( A+A, 0.5 );
     50 
     51 	flg = true;
     52 	while ( flg === true ) {
     53 		s = randn();
     54 		x = 0.5 * ( 1.0+(s/t) );
     55 		if ( x >= 0.0 && x <= 1.0 ) {
     56 			u = randu();
     57 			s4 = pow( s, 4.0 );
     58 			y = (8.0*alpha) - 12.0;
     59 			y = 1.0 - (s4 / y);
     60 			if ( u <= y ) {
     61 				flg = false;
     62 			} else {
     63 				y += 0.5 * pow( s4/((8.0*alpha)-8.0), 2.0 );
     64 				if ( u < y ) {
     65 					y = A * ln( 4.0*x*(1.0-x) );
     66 					y += s*s / 2.0;
     67 					if ( y >= ln( u ) ) {
     68 						flg = false;
     69 					}
     70 				}
     71 			}
     72 		}
     73 	}
     74 	return x;
     75 }
     76 
     77 
     78 // EXPORTS //
     79 
     80 module.exports = sample;