MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / harmonic

Method harmonic

src/main/java/com/thealgorithms/maths/Means.java:103–108  ·  view source on GitHub ↗

Computes the harmonic mean of the given numbers. The harmonic mean is calculated as: n / (1/x₁ + 1/x₂ + ... + 1/xₙ) Example: For numbers [1, 2, 4], the harmonic mean is 3/(1/1 + 1/2 + 1/4) = 3/1.75 ≈ 1.714 Note: This method will produce unexpected results if any input number is

(final Iterable<Double> numbers)

Source from the content-addressed store, hash-verified

101 * @see <a href="https://en.wikipedia.org/wiki/Harmonic_mean">Harmonic Mean</a>
102 */
103 public static Double harmonic(final Iterable<Double> numbers) {
104 checkIfNotEmpty(numbers);
105 double sumOfReciprocals = StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + 1d / y);
106 int size = IterableUtils.size(numbers);
107 return size / sumOfReciprocals;
108 }
109
110 /**
111 * Computes the quadratic mean (root mean square) of the given numbers.

Calls 3

checkIfNotEmptyMethod · 0.95
streamMethod · 0.80
sizeMethod · 0.65