Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python statistics geometric.mean() Function



The python statistics.geometric_mean() function is an iterable function, that converts data to floats and calculates the geometric mean.

If the function contains a zero or negative value, then this raises StatisticsError.

Syntax

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

statistics.geometric_mean(data, weights=None)

Parameter

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 or iterator.

Example 1

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

import statistics
x = statistics.geometric_mean([54, 24, 36])
print(x)

Output

The result obtained is as follows −

36.000000000000014

Example 2

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

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

Output

This produces the following result −

3.576344906149784

Example 3

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

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

Output

The result is obtained as follows −

0.27798904219477544

Example 4

If we pass datatype other than double or integer to statistics.geometric_mean() function, then it will throw error. In the below example we are passing string value, hence the code returns TypeError.

import statistics
x = statistics.geometric_mean("welcome to tutorialspoint")
print(x)

Output

The output obtained is as follows −

Traceback (most recent call last):
  File "/usr/lib/python3.10/statistics.py", line 344, in fmean
    n = len(data)
TypeError: object of type 'map' has no len()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/91470/main.py", line 2, in <module>
    x = statistics.geometric_mean("welcome to tutorialspoint")
  File "/usr/lib/python3.10/statistics.py", line 374, in geometric_mean
    return exp(fmean(map(log, data)))
  File "/usr/lib/python3.10/statistics.py", line 352, in fmean
    total = fsum(count(data))
  File "/usr/lib/python3.10/statistics.py", line 350, in count
    for n, x in enumerate(iterable, start=1):
TypeError: must be real number, not str
python_modules.htm
Advertisements