time-to-botec

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

renormalizing.js (1775B)


      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 /**
     22 * Samples without replacement from a discrete set using custom probabilities.
     23 *
     24 * ## Notes
     25 *
     26 * -   After each draw, the probabilities of the remaining observations are renormalized so that they sum to one.
     27 *
     28 *
     29 * @private
     30 * @param {ArrayLike} x - array-like object from which to sample
     31 * @param {NonNegativeInteger} size - sample size
     32 * @param {Function} rand - PRNG for generating uniformly distributed numbers
     33 * @param {ProbabilityArray} probabilities - element probabilities
     34 * @returns {Array} sample
     35 */
     36 function renormalizing( x, size, rand, probabilities ) {
     37 	var probs;
     38 	var psum;
     39 	var out;
     40 	var N;
     41 	var i;
     42 	var j;
     43 	var k;
     44 	var u;
     45 
     46 	N = x.length;
     47 	probs = new Array( N );
     48 	for ( i = 0; i < N; i++ ) {
     49 		probs[ i ] = probabilities[ i ];
     50 	}
     51 	out = new Array( size );
     52 	for ( i = 0; i < size; i++ ) {
     53 		u = rand();
     54 		psum = 0;
     55 		for ( j = 0; j < N; j++ ) {
     56 			psum += probs[ j ];
     57 			if ( u < psum ) {
     58 				break;
     59 			}
     60 		}
     61 		for ( k = 0; k < N; k++ ) {
     62 			if ( k === j ) {
     63 				continue;
     64 			}
     65 			probs[ k ] /= 1.0 - probs[ j ];
     66 		}
     67 		probs[ j ] = 0.0;
     68 		out[ i ] = x[ j ];
     69 	}
     70 	return out;
     71 }
     72 
     73 
     74 // EXPORTS //
     75 
     76 module.exports = renormalizing;