Skip to content

Add StandardDeviation.java #3039

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/main/java/com/thealgorithms/maths/StandardDeviation.java
Original file line number Diff line number Diff line change
@@ -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);
}

}
Original file line number Diff line number Diff line change
@@ -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);
}
}