Navy Seal
Navy Seal

Reputation: 125

Finding the sequence of the recursive formula

The sequence is defined by

$$ x_0 = 1 $$

$$ x_n = {1 + x_{n-1}}^(0.5) $$

I am trying to find out the limit to the nth integer but for some reason my x_1 value does not carry to the third element.

Here is my code:

def recursion (x):
x_0 = 1
x_1 = (2)**(0.5)
lst = [1]

while  len(lst) <= x:
    x_0, x_1 = x_1, ((1+x_0)**(1/2))
    lst.append(x_0)
print(lst)

It works for the first 2 elements only.

enter image description here

This is what I want it to doenter image description here

Upvotes: 0

Views: 71

Answers (2)

glibdud
glibdud

Reputation: 7840

The problem is here:

x_0, x_1 = x_1, ((1+x_0)**(1/2))

You're calculating x_0 and x_1 at the same time, but your formula for the new x_1 expects x_0 to have already been updated. If you split them up, you should get what you expect:

x_0 = x_1
x_1 = (1+x_0)**(1/2)

You're keeping more values than you need to, though. You only need one initializing value, and instead of having intermediate variables you can just read from the top of the lst:

lst = [1.0]
while len(lst) <= x:
    lst.append((1+lst[-1])**(0.5))

Upvotes: 1

Harald Nordgren
Harald Nordgren

Reputation: 12381

You tagged your question with python-3.x but your seem to be running this with Python 2. I don't know why, but in Python2 I get [1, 1.4142135623730951, 1, 1.0, 1, 1.0, 1, 1.0, 1, 1.0, 1] whereas Python3 returns the correct sequence.

Upvotes: 1

Related Questions