Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is the statistics.geometric_mean() function in Python?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss how to use the statistics.geometric_mean() function in Python.

Introduction

The statistics module in Python is an extremely useful module that provides functions to calculate mathematical statistics of numeric data.

The statistics module supports both int and float type numeric data. Some of the functions in the statistics module in Python include:

  • mean()
  • median()
  • mode()
  • geometric_mean()
  • harmonic_mean()

Geometric mean

The geometric mean is referred to as the nthn^{th} root of the product of nn numbers. Say we have a set of numbers, x1,x2,x3x_1, x_2, x_3, … xnx_n. The geometric mean is defined as:

i=1n\prod_{i=1}^nxinx_{i}^{n} = x1x2x3n\sqrt[n]{x_1x_2x_3}

For example, let the list of numbers be 54, 24, 36. Their geometric mean is 54.24.363\sqrt[3]{54.24.36} = 36.

Code

Let’s take a look at the code snippet below.

import statistics
data = [54, 24, 36]
result = statistics.geometric_mean(data)
print(result)
Using the statistics.geometric_mean() function in Python

Explanation

  • In line 1, we import the statistics module to call geometric_mean().

  • In line 2, we provide a list of data whose geometric mean needs to be found.

  • In line 3, we compute the geometric mean of the provided numbers.

  • In line 4, we print the output, which is stored in result.

Note:

  • Module_name.function_name is the syntax for calling any function inside a module.
  • The output is not exactly 36 and has some floating points. This is because of the computational style of a machine. We can overcome this by using the round() function.

The statistics.geometric_mean() function comes in handy when we want to compute the central tendency of datasets.

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring