time-to-botec

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

sample3.js (1606B)


      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 exp = require( '@stdlib/math/base/special/exp' );
     24 var pow = require( '@stdlib/math/base/special/pow' );
     25 var ln = require( '@stdlib/math/base/special/ln' );
     26 
     27 
     28 // MAIN //
     29 
     30 /**
     31 * Handles general case.
     32 *
     33 * @private
     34 * @param {PRNG} rand - PRNG for uniformly 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( rand, alpha, beta ) {
     40 	var lx;
     41 	var ly;
     42 	var xy;
     43 	var u;
     44 	var v;
     45 	var x;
     46 	var y;
     47 	while ( true ) {
     48 		u = rand();
     49 		v = rand();
     50 		x = pow( u, 1.0/alpha );
     51 		y = pow( v, 1.0/beta );
     52 		xy = x + y;
     53 		if ( xy <= 1.0 ) {
     54 			if ( xy > 0.0 ) {
     55 				return x / ( xy );
     56 			}
     57 			lx = ln( u ) / alpha;
     58 			ly = ln( v ) / beta;
     59 			if ( lx > ly ) {
     60 				ly -= lx;
     61 				lx = 0.0;
     62 			} else {
     63 				lx -= ly;
     64 				ly = 0.0;
     65 			}
     66 			return exp( lx - ln( exp(lx) + exp(ly) ) );
     67 		}
     68 	}
     69 }
     70 
     71 
     72 // EXPORTS //
     73 
     74 module.exports = sample;