hypergeometric.js (1902B)
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 hin = require( './hin.js' ); 24 25 26 // MAIN // 27 28 /** 29 * Returns a pseudorandom number drawn from a hypergeometric distribution. 30 * 31 * ## References 32 * 33 * - 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]. 34 * 35 * [@kachitvichyanukul:1985]: http://dx.doi.org/10.1080/00949658508810839 36 * 37 * 38 * @private 39 * @param {PRNG} rand - PRNG for uniformly distributed numbers 40 * @param {NonNegativeInteger} N - population size 41 * @param {NonNegativeInteger} K - subpopulation size 42 * @param {NonNegativeInteger} n - number of draws 43 * @returns {NonNegativeInteger} pseudorandom number 44 */ 45 function hypergeometric( rand, N, K, n ) { 46 var n1; 47 var n2; 48 var k; 49 var x; 50 51 if ( n > N/2 ) { 52 k = N - n; 53 if ( 2*K <= N ) { 54 n1 = K; 55 n2 = N - K; 56 x = hin( rand, n1, n2, k ); 57 return K - x; 58 } 59 n2 = K; 60 n1 = N - K; 61 x = hin( rand, n1, n2, k ); 62 return n - N + K + x; 63 } 64 k = n; 65 if ( 2*K <= N ) { 66 n1 = K; 67 n2 = N - K; 68 x = hin( rand, n1, n2, k ); 69 return x; 70 } 71 n1 = N - K; 72 n2 = K; 73 x = hin( rand, n1, n2, k ); 74 return n - x; 75 } 76 77 78 // EXPORTS // 79 80 module.exports = hypergeometric;