Home > Back-end >  py sequence not returning results
py sequence not returning results

Time:10-11

I am trying a program in py where i have to compute the sequence [![enter image description here][1]][1]

until [![enter image description here][2]][2]

My code is:

def a(n):
    z=(n**10)
    return z


n=1
while a(n)<10:
    a(n)
    n =1
    print(a(n))

But i get nothing in return. How off am I?

CodePudding user response:

Your while loop condition is not true on the first iteration so it never runs.

abs(a(n)-a(n-1)) is 0.01 when n=1, which is not less than 10**-6

CodePudding user response:

I believe your condition should be reversed, in that you want the while loop to continue until the condition becomes false. So, you can reverse the condition like this:

def a(n):
    z = (n**100/100**n)
    return z

n=1
while abs(a(n)-a(n-1)) > 10**-6:  # notice the inverted test
    print(n, a(n), abs(a(n)-a(n-1)))
    n =1

To make the code a bit more readable at each iteration, this is another option:

while True:
    delta = abs(a(n) - a(n-1))
    print('Calculating ', n, delta) 
    if delta <= 10**-6:
        print('Last iteration on n=', n)
        break
    n  = 1
  • Related