![]() |
VOOZH | about |
Given an array of elements, find harmonic mean of numbers.
Examples:
Input : arr[] = {2.0, 1.0}
Output : 1.3333
Harmonic mean = 2/(1/2.0 + 1/1.0)
= (2 * 2)/3
= 1.333
Input : arr[] = {13.5, 14.5, 14.8, 15.2, 16.1}
Output : 14.7707
Harmonic mean is used when average of rates is required, below is the formula.
Harmonic mean of n numbers x1, x2,
x3, . . ., xn can written as below.
Harmonic mean = n / ((1/x1) + (1/x2) + (1/x3) + . . . + (1/xn))
Below is the implementation of Harmonic Mean.
Output:
14.7707
Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.
What if we are given elements and their frequencies?
If we are given n numbers and every number has some frequency then simply we use formula
Harmonic mean = (Frequency-Sum) /((f1/x1) + (f2/x2) + (f3/x3) + . . . + (fn/xn))
Where f1, f2, f3, . . ., fn are the frequencies of elements and x1, 2, x3, . . ., xn are the elements of array.
Frequency-Sum = f1 + f2 + f3, . . ., fn
Examples:
Input : num[] = {13, 14, 15, 16, 17}
freq[] = {2, 5, 13, 7, 3}
Output : 15.0631
Output:
15.0631
Time Complexity: O(n)
Auxiliary Space: O(1)
Harmonic mean of numbers using harmonic_mean() in Python:
Simple Python program to find harmonic mean using harmonic_mean() function.
Output: 14.770680729373778
Time Complexity: O(n)
Auxiliary Space: O(1)