Skip to content

Commit c52b2a6

Browse files
authored
Add Standard Deviation (TheAlgorithms#3039)
1 parent 1a230bd commit c52b2a6

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.maths;
2+
3+
public class StandardDeviation {
4+
5+
public static double stdDev(double[] data)
6+
{
7+
double var = 0;
8+
double avg = 0;
9+
for (int i = 0; i < data.length; i++)
10+
{
11+
avg += data[i];
12+
}
13+
avg /= data.length;
14+
for (int j = 0; j < data.length; j++)
15+
{
16+
var += Math.pow((data[j] - avg), 2);
17+
}
18+
var /= data.length;
19+
return Math.sqrt(var);
20+
}
21+
22+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.maths;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class StandardDeviationTest{
7+
@Test
8+
void test1()
9+
{
10+
double[] t1 = new double[]{1,1,1,1,1};
11+
Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0);
12+
}
13+
@Test
14+
void test2()
15+
{
16+
double[] t2 = new double[]{1,2,3,4,5,6,7,8,9,10};
17+
Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143);
18+
}
19+
@Test
20+
void test3()
21+
{
22+
double[] t3= new double[]{1.1, 8.5, 20.3, 2.4, 6.2};
23+
Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265);
24+
}
25+
@Test
26+
void test4()
27+
{
28+
double[] t4 = new double[]{3.14, 2.22222, 9.89898989, 100.00045, 56.7};
29+
Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775);
30+
}
31+
}
32+

0 commit comments

Comments
 (0)