Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 12b1023

Browse files
kmtGryffindor20pre-commit-ci[bot]tianyizheng02
authored
[ADDED] Implementation of Geometric Mean. (#10421)
* [ADDED] Implementation of Geometric Mean. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Rectified type hints * Typo * Apply suggestions from code review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
1 parent 91a22c2 commit 12b1023

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎maths/geometric_mean.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
The Geometric Mean of n numbers is defined as the n-th root of the product
3+
of those numbers. It is used to measure the central tendency of the numbers.
4+
https://en.wikipedia.org/wiki/Geometric_mean
5+
"""
6+
7+
8+
def compute_geometric_mean(*args: int) -> float:
9+
"""
10+
Return the geometric mean of the argument numbers.
11+
>>> compute_geometric_mean(2,8)
12+
4.0
13+
>>> compute_geometric_mean('a', 4)
14+
Traceback (most recent call last):
15+
...
16+
TypeError: Not a Number
17+
>>> compute_geometric_mean(5, 125)
18+
25.0
19+
>>> compute_geometric_mean(1, 0)
20+
0.0
21+
>>> compute_geometric_mean(1, 5, 25, 5)
22+
5.0
23+
>>> compute_geometric_mean(2, -2)
24+
Traceback (most recent call last):
25+
...
26+
ArithmeticError: Cannot Compute Geometric Mean for these numbers.
27+
>>> compute_geometric_mean(-5, 25, 1)
28+
-5.0
29+
"""
30+
product = 1
31+
for number in args:
32+
if not isinstance(number, int) and not isinstance(number, float):
33+
raise TypeError("Not a Number")
34+
product *= number
35+
# Cannot calculate the even root for negative product.
36+
# Frequently they are restricted to being positive.
37+
if product < 0 and len(args) % 2 == 0:
38+
raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.")
39+
mean = abs(product) ** (1 / len(args))
40+
# Since python calculates complex roots for negative products with odd roots.
41+
if product < 0:
42+
mean = -mean
43+
# Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996
44+
possible_mean = float(round(mean))
45+
# To check if the rounded number is actually the mean.
46+
if possible_mean ** len(args) == product:
47+
mean = possible_mean
48+
return mean
49+
50+
51+
if __name__ == "__main__":
52+
from doctest import testmod
53+
54+
testmod(name="compute_geometric_mean")
55+
print(compute_geometric_mean(-3, -27))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /