iqr.js (1930B)
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 floor = require( '@stdlib/math/base/special/floor' ); 24 25 26 // FUNCTIONS // 27 28 /** 29 * Comparator function used to sort values in ascending order. 30 * 31 * @private 32 * @param {number} a - first number 33 * @param {number} b - second number 34 * @returns {number} difference between `a` and `b` 35 */ 36 function ascending( a, b ) { 37 return a - b; 38 } 39 40 /** 41 * Computes a quantile of the values in a numeric array. 42 * 43 * @private 44 * @param {NumericArray} arr - sorted 1d array 45 * @param {Probability} p - quantile prob [0,1] 46 * @returns {number} quantile 47 */ 48 function quantile( arr, p ) { 49 var len = arr.length; 50 var id; 51 var h; 52 h = ( ( len - 1.0 ) * p ) + 1.0; 53 id = floor( h ) - 1.0; 54 return arr[ id ] + ( ( h - floor( h ) ) * ( arr[ id + 1 ] - arr[ id ] ) ); 55 } 56 57 58 // MAIN // 59 60 /** 61 * Computes the inter-quartile range for a numeric array. 62 * 63 * @private 64 * @param {NumericArray} data - ndarray like data 65 * @param {number} j - column index for which to get the IQR 66 * @returns {number} inter-quartile range 67 */ 68 function iqr( data, j ) { 69 // Copy and sort data --> build X 70 var arr; 71 var i; 72 arr = new Array( data.shape[0] ); 73 for ( i = 0; i < data.shape[0]; i++ ) { 74 arr[ i ] = data.get( i, j ); 75 } 76 arr.sort( ascending ); 77 return quantile( arr, 0.75 ) - quantile( arr, 0.25 ); 78 } 79 80 81 // EXPORTS // 82 83 module.exports = iqr;