Problem 3. (Geometric and Harmonic Means) Write a program means.py that reads in
ID: 3924559 • Letter: P
Question
Problem 3. (Geometric and Harmonic Means) Write a program means.py that reads in positive real numbers from standard input and writes their geometric and harmonic means. The geometric mean of n positive numbers x1,x2,...,xn is (x1 × x2 × · · · × xn )1/n and their harmonic mean is n/(1/x1 + 1/x2 + · · · + 1/xn ). Hint: for the geometric mean, consider taking logarithms to avoid overflow.
means.py =
# means.py: reads in positive real numbers from standard input and writes their
# geometric and harmonic means.
import math
import stdio
# Read floats from standard input into a list a.
a = ...
# Define a variable n storing the length of a.
n = ...
# Define variables gm and hm to store the geometric and harmonic means of
# the numbers in a.
gm = ...
hm = ...
# Iterate over the values in a and calculate their geometric and harmonic
# means. For geometric mean, consider taking logarithms to avoid overflow.
for v in a:
...
...
# Write the results (geometric and harmonic means).
...
Explanation / Answer
import math
a = []
n= int(raw_input("How many numbers are you going to enter?"))
for i in range(0,n):
a.append(int(raw_input("Enter the next number:")))
s = 0
hm = 0.0
for i in range(0,n):
s = s + math.log(a[i])
hm = hm + (1.0/a[i])
#print(hm)
s = s - math.log(n)
gm = math.exp(s)
hm = n*hm
print("The geometric mean is "+str(gm))
print("The harmonic mean is "+str(hm))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.