From 69703d882d96a53168e7091b9bbe86c6f67056cd Mon Sep 17 00:00:00 2001 From: Rakshit Menpara Date: Fri, 1 Aug 2014 14:58:50 +0530 Subject: [PATCH] Fixed correlation coefficient calculation * Correlation coefficient r() was returning NaN if the standard deviation of y was 0 (because all y values were equal) * Added test for calculating linear regression with points containing same y coordinate values --- lib/stats.js | 6 +++++- test/test.js | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/stats.js b/lib/stats.js index c875a34..5b54d12 100644 --- a/lib/stats.js +++ b/lib/stats.js @@ -316,7 +316,11 @@ return (num - meanX) / stdDevX; }); yCoords.map(function(num) { - return (num - meanY) / stdDevY; + if (stdDevY === 0) { + return 0; + } else { + return (num - meanY) / stdDevY; + } }); // Multiply each element in the x by the corresponding value in diff --git a/test/test.js b/test/test.js index 03baea9..12b64fd 100644 --- a/test/test.js +++ b/test/test.js @@ -128,6 +128,20 @@ describe('#linReg()', function() { expect(reg.yIntercept).to.be.within(.00001).of(3.61352); expect(reg.r).to.be.within(.000001).of(-.693356); }); + + it('should not return NaN if the y coordinate values are same', function() { + var reg1 = stats([ + { x: 1, y: 4 }, + { x: 3, y: 4 }, + { x: 6, y: 4 }, + { x: 4, y: 4 }, + { x: 9, y: 4 }, + ]).linReg(); + + expect(reg1.slope).to.eql(0); + expect(reg1.yIntercept).to.eql(4); + expect(reg1.r).to.eql(0); + }); }); describe('#powReg()', function() {