stdev.js (1603B)
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 sqrt = require( '@stdlib/math/base/special/sqrt' ); 24 25 26 // MAIN // 27 28 /** 29 * Computes the unbiased standard deviation. 30 * 31 * @private 32 * @param {ndarrayLike} arr - input array 33 * @param {number} j - column for which to calculate the standard deviation 34 * @returns {number} standard deviation 35 * 36 * @example 37 * var ndarrayLike = require( './ndarray_like.js' ); 38 * 39 * var x = [ 0.6333, 0.8643, 1.0952, 1.3262, 1.5571, 1.7881, 2.019, 2.25, 2.481, 2.7119 ]; 40 * var y = [ -0.0468, 0.8012, 1.6492, 2.4973, 3.3454, 4.1934, 5.0415, 5.8896, 6.7376, 7.5857 ]; 41 * var arr = ndarrayLike( x, y ); 42 * var out = stdev( arr, 1 ); 43 * // returns ~2.568 44 */ 45 function stdev( arr, j ) { 46 var delta; 47 var mean; 48 var M2; 49 var i; 50 var x; 51 delta = 0.0; 52 mean = 0.0; 53 M2 = 0.0; 54 55 for ( i = 0; i < arr.shape[0]; i++ ) { 56 x = arr.get( i, j ); 57 delta = x - mean; 58 mean += delta / ( i+1 ); 59 M2 += delta * ( x - mean ); 60 } 61 return sqrt( M2 / ( i - 1 ) ); 62 } 63 64 65 // EXPORTS // 66 67 module.exports = stdev;