Home > Backend Development > Python Tutorial > How Can I Calculate the Arithmetic Mean of a List in Python Efficiently and Accurately?

How Can I Calculate the Arithmetic Mean of a List in Python Efficiently and Accurately?

Mary-Kate Olsen
Release: 2024-12-03 00:58:12
Original
278 people have browsed it

How Can I Calculate the Arithmetic Mean of a List in Python Efficiently and Accurately?

Finding the Arithmetic Mean of a List in Python

Calculating the average of a list in Python involves the arithmetic mean, represented as the sum of all values divided by the number of values. Here are various approaches, focusing specifically on numerical stability:

For Python 3.8 and higher, the recommended method is to utilize the statistics.fmean function, which offers improved accuracy for floating-point calculations:

import statistics
list_of_numbers = [1, 2, 3, 4]
average = statistics.fmean(list_of_numbers)
print(average)  # Output: 2.5
Copy after login

For Python 3.4 and later, the statistics.mean function can be employed for numerical stability with floats:

import statistics
list_of_numbers = [15, 18, 2, 36, 12, 78, 5, 6, 9]
average = statistics.mean(list_of_numbers)
print(average)  # Output: 20.11111111111111
Copy after login

In earlier versions of Python 3, a simple calculation using the sum() and len() functions can be used, ensuring that the division results in a float:

list_of_numbers = [1, 2, 3, 4]
average = sum(list_of_numbers) / len(list_of_numbers)
print(average)  # Output: 2.5
Copy after login

For Python 2, casting the length of the list to a float ensures float division:

list_of_numbers = [1, 2, 3, 4]
average = sum(list_of_numbers) / float(len(list_of_numbers))
print(average)  # Output: 2.5
Copy after login

The above is the detailed content of How Can I Calculate the Arithmetic Mean of a List in Python Efficiently and Accurately?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template