time-to-botec

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

main.js (2134B)


      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 isTypedArray = require( './../../is-typed-array' );
     24 var isArray = require( './../../is-array' );
     25 var isNumber = require( './../../is-number' ).isPrimitive;
     26 var absdiff = require( '@stdlib/math/base/utils/absolute-difference' );
     27 var FLOAT64_SQRT_EPS = require( '@stdlib/constants/float64/sqrt-eps' );
     28 
     29 
     30 // MAIN //
     31 
     32 /**
     33 * Tests if a value is an array of probabilities that sum to one.
     34 *
     35 * @param {*} v - value to test
     36 * @returns {boolean} boolean indicating if a value is a probability array
     37 *
     38 * @example
     39 * var bool = isUnityProbabilityArray( [ 0.25, 0.5, 0.25 ] );
     40 * // returns true
     41 *
     42 * @example
     43 * var bool = isUnityProbabilityArray( new Uint8Array( [ 0, 1 ] ) );
     44 * // returns true
     45 *
     46 * @example
     47 * var bool = isUnityProbabilityArray( [ 0.4, 0.4, 0.4 ] );
     48 * // returns false
     49 *
     50 * @example
     51 * var bool = isUnityProbabilityArray( [ 3.14, 0.0 ] );
     52 * // returns false
     53 */
     54 function isUnityProbabilityArray( v ) {
     55 	var sum;
     56 	var i;
     57 	if ( isArray( v ) ) {
     58 		sum = 0.0;
     59 		for ( i = 0; i < v.length; i++ ) {
     60 			if (
     61 				!isNumber( v[ i ] ) ||
     62 				v[ i ] > 1.0 ||
     63 				v[ i ] < 0.0
     64 			) {
     65 				return false;
     66 			}
     67 			sum += v[ i ];
     68 		}
     69 		return ( absdiff( sum, 1.0 ) <= FLOAT64_SQRT_EPS );
     70 	}
     71 	if ( isTypedArray( v ) ) {
     72 		sum = 0.0;
     73 		for ( i = 0; i < v.length; i++ ) {
     74 			if (
     75 				v[ i ] > 1.0 ||
     76 				v[ i ] < 0.0
     77 			) {
     78 				return false;
     79 			}
     80 			sum += v[ i ];
     81 		}
     82 		return ( absdiff( sum, 1.0 ) <= FLOAT64_SQRT_EPS );
     83 	}
     84 	return false;
     85 }
     86 
     87 
     88 // EXPORTS //
     89 
     90 module.exports = isUnityProbabilityArray;