time-to-botec

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

pcorr.js (1750B)


      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 max = require( '@stdlib/math/base/special/max' );
     24 var min = require( '@stdlib/math/base/special/min' );
     25 var sqrt = require( '@stdlib/math/base/special/sqrt' );
     26 var variance = require( './../../base/variance' );
     27 var mean = require( './../../base/mean' );
     28 
     29 
     30 // MAIN //
     31 
     32 /**
     33 * Computes the Pearson product-moment correlation coefficient between `x` and `y`.
     34 *
     35 * @private
     36 * @param {NumericArray} x - first data array
     37 * @param {NumericArray} y - second data array
     38 * @returns {number} correlation coefficient
     39 *
     40 * @example
     41 * var x = [ 1.0, 2.0, 2.0, 1.0 ];
     42 * var y = [ 1.8, 2.2, 2.5, 1.4 ];
     43 * var r = pcorr( x, y );
     44 * // returns ~0.905
     45 */
     46 function pcorr( x, y ) {
     47 	var denom;
     48 	var num;
     49 	var out;
     50 	var xy;
     51 	var xm;
     52 	var ym;
     53 	var i;
     54 	var n;
     55 
     56 	n = x.length;
     57 	xm = mean( n, x, 1 );
     58 	ym = mean( n, y, 1 );
     59 	xy = 0.0;
     60 	for ( i = 0; i < n; i++ ) {
     61 		xy += x[ i ] * y[ i ];
     62 	}
     63 	num = xy - ( n * xm * ym );
     64 	denom = ( n-1 ) * sqrt(variance(n, 1, x, 1)) * sqrt(variance(n, 1, y, 1) );
     65 	out = num / denom;
     66 
     67 	// Handle rounding errors:
     68 	return max( min( out, 1.0 ), -1.0 );
     69 }
     70 
     71 
     72 // EXPORTS //
     73 
     74 module.exports = pcorr;