Rickjames59
Rickjames59

Reputation: 1

trying to approximate e using while loops in python

I'm supposed to approximate the value of e by using 1 + 1/1 + 1/2 +1/3 and so on, up to the amount that the user entered (like 10 would be up to one tenth) i have most of it figured out but cant get the right output here's what I've got

def iterationE(e):
    count = 0
    num = 1
    while count <= e:
        count = count + 1
        num = 1 + 1/count
    return num
e = int(input ("enter the number of iterations for e: "))
print(iterationE(e))

Upvotes: 0

Views: 1219

Answers (1)

tom10
tom10

Reputation: 69242

You were very close. I think this should work. Basically, you needed to increment num in each loop cycle.

def iterationE(e):
    count = 1
    num = 1
    while count <= e:
        num += 1./count
        count = count + 1
    return num
e = int(input ("enter the number of iterations for e: "))
print(iterationE(e))

This is, by the way, what's known as the Harmonic Series, and it does not converge to e, and, in fact does not even converge.

I think a reasonable step would be first, though, to get this harmonic series to behave as you expect, and then work on the Taylor Series expression for e as the next step.

Upvotes: 1

Related Questions