Python statistics harmonic.mean() Function



The Python statistics.harmonic_mean() is a sequence of iterable real-valued numbers. The Harmonic mean is a numeric average calculated by dividing the number of observations, or entries in the series, by the reciprocal of each number in the series.

It is an infinite series that never converges to a limit. Harmonic mean gives less weight to the larger values and more weight to the smaller values to balance the values properly.

The harmonic mean is calculated as :

If we consider four values, i.e., (a, b, c, d), this will be equivalent to 4/(1/a + 1/b + 1/c + 1/d).

Syntax

Following is the basic syntax of the statistics.geometric_mean() function −

statistics.harmonic_mean(data, weights=None)

Parameters

Here, the data and weight values can be used as any sequence, list or iterator.

Return Value

This function always returns a float arithmetic mean of data, which can be a sequence of iterations.

Example 1

In the below example, we are calculating the arithmetic mean of the given data using the statistics.harmonic_mean() function.

import statistics
x = statistics.harmonic_mean([40, 60])
print(x)

Output

The result is produced as follows −

48.0

Example 2

Here we are calculating the arithmetic mean for the float values using the statistics.harmonic_mean() function.

import statistics
x = statistics.harmonic_mean([0.54, 2.34, 36.2])
print(x)

Output

This produces the following result −

1.3004878714475796

Example 3

Now, we are passing decimal values to find the mean of the given data using statistics.harmonic_mean() function.

import statistics
from decimal import Decimal as D
x = statistics.harmonic_mean([D("0.15"), D("0.175"), D("0.65"), D("0.35")])
print(x)

Output

The result is obtained as follows −

0.2384279475982532751091703057
python_modules.htm
Advertisements