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

Python statistics fmean() Function



The Python statistics.fmean() function converts data to floats by using the arithmetic mean.

The fmean function runs faster than the mean() and always returns a float. This functions contains a sequence of iterable data. Whenever the input data is empty then it throws StatisticsError.

Syntax

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

statistics.fmean(data, weights=None)

Parameters

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

Return Value

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

Example 1

In the below example we are calculating the average of the given float data using statistics.fmean() function.

import statistics
x = statistics.fmean([3.5, 4.0, 5.25])
print(x)

Output

The output obtained is as follows −

4.25

Example 2

Here, we are calculating the fmean of the given weights using statistics.fmean() function.

import statistics
weights = [0.20, 0.20, 0.30, 0.30]
x = statistics.fmean(weights)
print(x)

Output

This produces the following result −

0.25

Example 3

Now, we are passing decimal values to find their fmean using statistics.fmean() function.

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

Output

The result is obtained as follows −

0.33125

Example 4

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

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

Output

The output obtained is as follows −

Traceback (most recent call last):
  File "/home/cg/root/61842/main.py", line 2, in <module>
    x = statistics.fmean("welcome to tutorialspoint")
  File "/usr/lib/python3.10/statistics.py", line 354, in fmean
    total = fsum(data)
TypeError: must be real number, not str
python_modules.htm
Advertisements