Add Standard Deviation (#3039)

This commit is contained in:
RaghavTaneja
2022-05-01 02:32:03 -05:00
committed by GitHub
parent 1a230bd61e
commit c52b2a649c
2 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.thealgorithms.maths;
public class StandardDeviation {
public static double stdDev(double[] data)
{
double var = 0;
double avg = 0;
for (int i = 0; i < data.length; i++)
{
avg += data[i];
}
avg /= data.length;
for (int j = 0; j < data.length; j++)
{
var += Math.pow((data[j] - avg), 2);
}
var /= data.length;
return Math.sqrt(var);
}
}

View File

@ -0,0 +1,32 @@
package com.thealgorithms.maths;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class StandardDeviationTest{
@Test
void test1()
{
double[] t1 = new double[]{1,1,1,1,1};
Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0);
}
@Test
void test2()
{
double[] t2 = new double[]{1,2,3,4,5,6,7,8,9,10};
Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143);
}
@Test
void test3()
{
double[] t3= new double[]{1.1, 8.5, 20.3, 2.4, 6.2};
Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265);
}
@Test
void test4()
{
double[] t4 = new double[]{3.14, 2.22222, 9.89898989, 100.00045, 56.7};
Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775);
}
}