Reputation: 754
I'm trying to have this while loop give the same output as the for-loop, however, its infinitely recursive as opposed to stopping at the maximum average height.
The code looks like this:
import numpy as np
N = 5
h = np.zeros(N) # heights of family members (in meter)
h[0] = 1.60; h[1] = 1.85; h[2] = 1.75; h[3] = 1.80; h[4] = 0.50
sum = 0
i = 0
while i < 5:
sum = sum + h[i]
average = sum/n
print('average height: {:g} meter'.format(average))
This is the for loop I was trying to get the while loop of:
for i in [0, 1, 2, 3, 4]:
sum = sum + h[i]
average = sum/N
print(’Average height: {:g} meter’.format(average))
Where did I go wrong?
expected output:
average height 0.64 meter
average height 1.01 meter
average height 1.36 meter
average height 1.72 meter
average height 1.82 meter
Upvotes: 0
Views: 150
Reputation: 7273
It looks like you are trying to calculate the running average, printing the current value as you go. For this you don't need numpy... or do you?
Simply define a list containing your heights. Then iterate through it.
heights = [1.6, 1.85, 1.75, 1.80, 0.5]
running_sum = 0.0
running_average = 0.0
for height in heights:
running_sum += height
running_average = running_sum / len(heights)
print('Current average height: {:g} meter'.format(running_average))
It looks like the final value for the average height in the family is 1.5, not really 1.82, as your expected output says. Which can be verified with WolframAlpha. We have another problem too it seems. Your running average so far divides by the total length (5) every time, when we should divide by the length thus far. That's something you might want to use numpy for. For that, see this question on running averages.
Old answer below:
Remember to increment the counter i
:
Remember that sum
is already defined in Python. So I changed it's name to s
, and collapsed the operation s = s + h[i]
to s += h[i]
i = 0
while i < 5:
s += h[i]
average = sum/n
print('average height: {:g} meter'.format(average))
i+=1
Upvotes: 4
Reputation: 2277
Martin Kleiven's answer does solve the repeating problem, but it gives an error. here is the correct answer:
Remember to increment the counter i
:
import numpy as np
N = 5
h = np.zeros(N) # heights of family members (in meter)
h[0] = 1.60; h[1] = 1.85; h[2] = 1.75; h[3] = 1.80; h[4] = 0.50
s = 0
i = 0
while i < 5:
s = s + h[i] # by the way, sum is already defined in python, so change the variable name.
average = s/N # Change it to n => N
print('average height: {:g} meter'.format(average))
i += 1
Upvotes: 0