Chad Johnson
Chad Johnson

Reputation: 21905

What is wrong with my code to calculate a standard deviation?

I'm trying to calculate the standard deviation of a set of numbers as Excel would with the STDEVPA() function, but I'm not getting the correct result. I'm following this formula:

enter image description here

Here is my [Node] code:

var _ = require('underscore');

var prices = [
    1.37312,
    1.35973,
    1.35493,
    1.34877,
    1.34853,
    1.35677,
    1.36079,
    1.36917,
    1.36769,
    1.3648,
    1.37473,
    1.37988,
    1.37527,
    1.38053,
    1.37752,
    1.38652,
    1.39685,
    1.39856,
    1.39684,
    1.39027
];

var standardDeviation = 0;

var average = _(prices).reduce(function(total, price) {
    return total + price;
}) / prices.length;

var squaredDeviations = _(prices).reduce(function(total, price) {
    var deviation = price - average;
    var deviationSquared = deviation * deviation;

    return total + deviationSquared;
});

var standardDeviation = Math.sqrt(squaredDeviations / prices.length);

console.log(standardDeviation);

When I run this, I get 0.26246286981807065, and instead I should get 0.0152.

Please note that I posted on StackOverflow and not the Mathematics site because, in my opinion, this is more geared toward programming than mathematics. If I post there, they will tell me to post here because this is related to programming.

Upvotes: 0

Views: 1581

Answers (1)

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 18607

If you console.log(total) inside your calculation of squaredDeviations, you'll see you're starting out with the value 1.37312, namely the first thing in your list. You need to explicitly tell it to start at 0, which is the third optional argument to reduce. Just replace:

var squaredDeviations = _(prices).reduce(function(total, price) {
    var deviation = price - average;
    var deviationSquared = deviation * deviation;

    return total + deviationSquared;
});

with

var squaredDeviations = _(prices).reduce(function(total, price) {
    var deviation = price - average;
    var deviationSquared = deviation * deviation;

    return total + deviationSquared;
}, 0);

See the underscore documentation for more details. In particular, note that things work when calculating the mean without passing this additional argument because, in said case, the iteratee function will not be applied to the first element.

Upvotes: 3

Related Questions