time-to-botec

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

main.js (2138B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2019 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 isIteratorLike = require( '@stdlib/assert/is-iterator-like' );
     24 var hasOwnProp = require( '@stdlib/assert/has-own-property' );
     25 var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
     26 var incrvariance = require( './../../../incr/variance' );
     27 
     28 
     29 // MAIN //
     30 
     31 /**
     32 * Computes the unbiased sample variance over all iterated values.
     33 *
     34 * @param {Iterator} iterator - input iterator
     35 * @param {number} [mean] - mean value
     36 * @throws {TypeError} first argument must be an iterator
     37 * @throws {TypeError} second argument must be a number
     38 * @returns {(number|null)} unbiased sample variance
     39 *
     40 * @example
     41 * var runif = require( '@stdlib/random/iter/uniform' );
     42 *
     43 * var rand = runif( -10.0, 10.0, {
     44 *     'iter': 100
     45 * });
     46 *
     47 * var s2 = itervariance( rand );
     48 * // returns <number>
     49 */
     50 function itervariance( iterator, mean ) {
     51 	var acc;
     52 	var v;
     53 	if ( !isIteratorLike( iterator ) ) {
     54 		throw new TypeError( 'invalid argument. First argument must be an iterator. Value: `'+iterator+'`.' );
     55 	}
     56 	if ( arguments.length > 1 ) {
     57 		if ( !isNumber( mean ) ) {
     58 			throw new TypeError( 'invalid argument. Second argument must be a number primitive. Value: `' + mean + '`.' );
     59 		}
     60 		acc = incrvariance( mean );
     61 	} else {
     62 		acc = incrvariance();
     63 	}
     64 	while ( true ) {
     65 		v = iterator.next();
     66 		if ( typeof v.value === 'number' ) {
     67 			acc( v.value );
     68 		} else if ( hasOwnProp( v, 'value' ) ) {
     69 			acc( NaN );
     70 		}
     71 		if ( v.done ) {
     72 			break;
     73 		}
     74 	}
     75 	return acc();
     76 }
     77 
     78 
     79 // EXPORTS //
     80 
     81 module.exports = itervariance;