How to do standard deviation in JavaScript
In this article, you will learn about how to do standard deviation in JavaScript.
The standard deviation is a measure of how spread out numbers are. It is the square root of the variance where the variance is defined as the average of the squared differences from the mean. To calculate the standard deviation of an array in JavaScript we need to follow a few steps as first we need to calculate the mean and then variance and finally deviation. For example, we have an array that contains these numbers – 2, 4, 4, 4, 5, 5, 7, 9. We will calculate the standard deviation of this array in the below section.
function standardDeviation(arr){
let mean = arr.reduce((acc, curr)=>{
return acc + curr
}, 0) / arr.length;
arr = arr.map((el)=>{
return (el - mean) ** 2
})
let total = arr.reduce((acc, curr)=> acc + curr, 0);
return Math.sqrt(total / arr.length)
}
console.log(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]))
//Output: 2
Here, we have calculated the standard deviation of a given array manually. We have calculated the mean and then variance and finally got the result of standard deviation that is 2. It is a statistical term that we have implemented and written a program of calculating it.
If this seems hard for you and you do not want to bear any hassle then you may use math.js. It is an extensive math library for JavaScript and NodeJS. Here, I will show you how you can use this in NodeJS. To do so I will first download this library by giving the command npm i mathjs. let’s see the example below:
const math = require('mathjs')
let arr = [2, 4, 4, 5, 7, 9]
let standardDeviation = math.std(arr)
console.log(standardDeviation)
//Output: 2.48327740429189
Here, we simply require the mathjs library and then apply the function math.std() that comes with this library for calculating standard deviation. Finally, we got the answer and that is 2.48327740429189 and you may calculate standard deviation in JavaScript by following these approaches.