- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathMeans.java
54 lines (47 loc) · 1.96 KB
/
Means.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
packagecom.thealgorithms.maths;
importjava.util.stream.StreamSupport;
importorg.apache.commons.collections4.IterableUtils;
/**
* https://en.wikipedia.org/wiki/Mean
* <p>
* by: Punit Patel
*/
publicfinalclassMeans {
privateMeans() {
}
/**
* @brief computes the [Arithmetic Mean](https://en.wikipedia.org/wiki/Arithmetic_mean) of the input
* @param numbers the input numbers
* @throws IllegalArgumentException empty input
* @return the arithmetic mean of the input numbers
*/
publicstaticDoublearithmetic(finalIterable<Double> numbers) {
checkIfNotEmpty(numbers);
returnStreamSupport.stream(numbers.spliterator(), false).reduce((x, y) -> x + y).get() / IterableUtils.size(numbers);
}
/**
* @brief computes the [Geometric Mean](https://en.wikipedia.org/wiki/Geometric_mean) of the input
* @param numbers the input numbers
* @throws IllegalArgumentException empty input
* @return the geometric mean of the input numbers
*/
publicstaticDoublegeometric(finalIterable<Double> numbers) {
checkIfNotEmpty(numbers);
returnMath.pow(StreamSupport.stream(numbers.spliterator(), false).reduce((x, y) -> x * y).get(), 1d / IterableUtils.size(numbers));
}
/**
* @brief computes the [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) of the input
* @param numbers the input numbers
* @throws IllegalArgumentException empty input
* @return the harmonic mean of the input numbers
*/
publicstaticDoubleharmonic(finalIterable<Double> numbers) {
checkIfNotEmpty(numbers);
returnIterableUtils.size(numbers) / StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + 1d / y);
}
privatestaticvoidcheckIfNotEmpty(finalIterable<Double> numbers) {
if (!numbers.iterator().hasNext()) {
thrownewIllegalArgumentException("Emtpy list given for Mean computation.");
}
}
}