time-to-botec

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

hin.js (2183B)


      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 factorial = require( '@stdlib/math/base/special/factorial' );
     24 
     25 
     26 // MAIN //
     27 
     28 /**
     29 * Returns a pseudorandom number drawn from a hypergeometric distribution using the HIN algorithm, which is based on an inverse transformation method.
     30 *
     31 * ## References
     32 *
     33 * -   Fishman, George S. 1973. _Concepts and methods in discrete event digital simulation_. A Wiley-Interscience Publication. New York, NY, USA: Wiley.
     34 * -   Kachitvichyanukul, Voratas., and Burce Schmeiser. 1985. "Computer generation of hypergeometric random variates." _Journal of Statistical Computation and Simulation_ 22 (2): 127–45. doi:[10.1080/00949658508810839][@kachitvichyanukul:1985].
     35 *
     36 * [@kachitvichyanukul:1985]: http://dx.doi.org/10.1080/00949658508810839
     37 *
     38 *
     39 * @private
     40 * @param {PRNG} rand - PRNG for uniformly distributed numbers
     41 * @param {NonNegativeInteger} n1 - number of successes in population
     42 * @param {NonNegativeInteger} n2 - number of failures in population
     43 * @param {NonNegativeInteger} k - number of draws
     44 * @returns {NonNegativeInteger} pseudorandom number
     45 */
     46 function hin( rand, n1, n2, k ) {
     47 	var p;
     48 	var u;
     49 	var x;
     50 	if ( k < n2 ) {
     51 		p = ( factorial( n2 ) * factorial( n1 + n2 - k ) ) /
     52 			( factorial( n1 + n2 ) * factorial( n2 - k ) );
     53 		x = 0;
     54 	} else {
     55 		p = ( factorial( n1 ) * factorial( k ) ) /
     56 			( factorial( k - n2 ) * factorial( n1 + n2 ) );
     57 		x = k - n2;
     58 	}
     59 	u = rand();
     60 	while ( u > p ) {
     61 		u -= p;
     62 		p *= ( n1 - x ) * ( k - x ) / ( ( x + 1 ) * ( n2 - k + 1 + x ) );
     63 		x += 1;
     64 	}
     65 	return x;
     66 }
     67 
     68 
     69 // EXPORTS //
     70 
     71 module.exports = hin;