Python statistics.harmonic_mean() Method

Python statistics 模块Python statistics Module

Python statistics.harmonic_mean()Used to calculate the harmonic mean of a given data set.

The harmonic mean is a method of calculating averages, used to calculate the average ratio of a set of numbers. It is calculated by taking the reciprocal of each number, calculating their arithmetic mean, and then taking the reciprocal of the result.

The method's parameter data is an iterable containing numeric values, such as a list or tuple. It calculates and returns the harmonic mean of the data set as the result.

The harmonic mean is calculated as follows:

If you have four data points (a, b, c and d), the calculation is:4 / (1/a + 1/b + 1/c + 1/d)。

Syntax

The syntax of the statistics.harmonic_mean() method is as follows:

statistics.harmonic_mean(data)

Parameter description:

  • data-- An iterable containing numeric values, such as a list or tuple.

Return Value

The function calculates and returns the harmonic mean of the data set as the result.

Example

The following example returns the arccosine of the specified numbers:

Example

import statistics

data = [2, 4, 8, 16]
harmonic_mean = statistics.harmonic_mean(data)
print(harmonic_mean)

Output result:

4.0

In the above example, the given data set is [2, 4, 8, 16], and the harmonic_mean() function calculates the harmonic mean as 4.0.

The harmonic mean is often used to handle data related to ratios and rates, such as speed, working time, and unit cost. It is very useful for dealing with reciprocal and proportional relationships, and can effectively handle some special cases, such as when calculating average speed or average efficiency.

Python statistics 模块Python statistics Module

Other extensions