forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
williamfiset#338 added standard deviation and tests for it
- Loading branch information
1 parent
c399405
commit 0b9e5a0
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
17 changes: 17 additions & 0 deletions
17
src/main/java/com/williamfiset/algorithms/math/StandardDeviation.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package com.williamfiset.algorithms.math; | ||
|
||
public class StandardDeviation { | ||
|
||
public static double SD(double arr[]) { | ||
double sum = 0, StandardDeviation = 0; | ||
int length = arr.length; | ||
for (double num : arr) { | ||
sum += num; | ||
} | ||
double mean = sum / length; | ||
for (double num : arr) { | ||
StandardDeviation = StandardDeviation + Math.pow(num - mean, 2); | ||
} | ||
return Math.sqrt((StandardDeviation / length)); | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
src/test/java/com/williamfiset/algorithms/math/StandardDeviationTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package com.williamfiset.algorithms.math; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import org.junit.Test; | ||
public class StandardDeviationTest { | ||
|
||
@Test | ||
public void StandardDeviation4(){ | ||
double[] array = {-1, -2, -3, -4, -5}; | ||
double result = StandardDeviation.SD(array); | ||
assertEquals(1.4142135623730951, result); | ||
} | ||
|
||
@Test | ||
public void StandardDeviation2(){ | ||
double[] array = {3, 5, 7, 20, 55, 12, 1, 3, 5, 4}; | ||
double result = StandardDeviation.SD(array); | ||
assertEquals(15.428869044748549, result); | ||
} | ||
} |