The statistics.fmean
function in Python's statistics
module calculates the arithmetic mean (average) of a given set of numbers using floating-point arithmetic. This function is particularly useful for maintaining precision in calculations with floating-point numbers.
Table of Contents
- Introduction
statistics.fmean
Function Syntax- Examples
- Basic Usage
- Mean of a List of Numbers
- Mean of a Tuple of Numbers
- Handling Different Types of Numeric Data
- Real-World Use Case
- Conclusion
Introduction
The statistics.fmean
function is part of the statistics
module, which provides functions for mathematical statistics of numeric data. The arithmetic mean is the sum of the data divided by the number of data points. Using floating-point arithmetic helps maintain precision, especially with large datasets or data with many decimal places.
statistics.fmean Function Syntax
Here's how you use the statistics.fmean
function:
import statistics
mean_value = statistics.fmean(data)
Parameters:
data
: A sequence or iterable of numeric data (list, tuple, etc.).
Returns:
- The arithmetic mean of the given data as a floating-point number.
Raises:
StatisticsError
: Ifdata
is empty.
Examples
Basic Usage
Calculate the mean of a list of numbers.
import statistics
data = [1, 2, 3, 4, 5]
mean_value = statistics.fmean(data)
print(f"Mean: {mean_value}")
Output:
Mean: 3.0
Mean of a List of Numbers
Calculate the mean of a list of integers.
import statistics
numbers = [10, 20, 30, 40, 50]
mean_value = statistics.fmean(numbers)
print(f"Mean of numbers: {mean_value}")
Output:
Mean of numbers: 30.0
Mean of a Tuple of Numbers
Calculate the mean of a tuple of floats.
import statistics
numbers = (1.5, 2.5, 3.5, 4.5, 5.5)
mean_value = statistics.fmean(numbers)
print(f"Mean of numbers: {mean_value}")
Output:
Mean of numbers: 3.5
Handling Different Types of Numeric Data
Calculate the mean of a mixed list of integers and floats.
import statistics
numbers = [1, 2.5, 3, 4.5, 5]
mean_value = statistics.fmean(numbers)
print(f"Mean of numbers: {mean_value}")
Output:
Mean of numbers: 3.2
Real-World Use Case
Calculating Average Temperature
Calculate the average temperature from a list of daily temperatures using floating-point arithmetic.
import statistics
temperatures = [22.5, 23.0, 21.5, 20.0, 22.0, 21.0, 23.5]
average_temperature = statistics.fmean(temperatures)
print(f"Average temperature: {average_temperature}")
Output:
Average temperature: 21.928571428571427
Conclusion
The statistics.fmean
function is a simple and effective way to calculate the arithmetic mean of a set of numbers in Python using floating-point arithmetic. It is particularly useful for maintaining precision in calculations with large datasets or data with many decimal places. This function makes it easy to determine the mean, which is a common requirement in various fields such as science, finance, and engineering.
Comments
Post a Comment
Leave Comment