Marvin Kropp
Marvin Kropp

Reputation: 25

Why does recursive sequence not work correctly?

I'm totally new to Python and I'm trying to print the solution for a recursive sequence:

#Input sequence variables

a = float(raw_input("type in a = "))
n0 = int(raw_input("type in n_0 = "))
n1 = int(raw_input("type in n_1 = "))
y0 = float(raw_input("type in y_0 = "))


#Define function y_n (forward iteration)

def yn(n):
   if (n==0):
       return y0
   else:
       return (1/n)-a*yn(n-1)

#backward iteration

def yn_back(n):
       return (1/a)*((1/n)-yn(n-1))

if(n1>=n0):
   for i in range(n0,n1+1):   
       print(yn(i))

else:
   for i in range(n0,n1+1):
       print(yn_back(i))

But if I run this script with a=5, n0=1, n1=30 and y0=log(5/6)=0.182322 the solutions are very high (from 0.08839 to 3.29e+18) and the values are negative for even n. The solution is right for n=1. For other n, the (1/n) in the definition of yn(n) seems to be ignored.

Can someone help me?

Thanks a lot!

Upvotes: 0

Views: 120

Answers (1)

Blender
Blender

Reputation: 298146

n is probably an integer, so 1/n is returning 0 for n greater than 1:

>>> 1/1
1
>>> 1/2
0
>>> 1.0/2
0.5

To make sure you're using float division, change 1 to 1.0 wherever you calculate 1/n:

(1.0/n)

Or convert n into a float.

Upvotes: 1

Related Questions