mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 01:35:16 +08:00
Add Standard Deviation (#3039)
This commit is contained in:
22
src/main/java/com/thealgorithms/maths/StandardDeviation.java
Normal file
22
src/main/java/com/thealgorithms/maths/StandardDeviation.java
Normal 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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user