Hendrra
Hendrra

Reputation: 859

Recursive formula of a sequence containing a function

I am to write a recursive sequence and print it's n first values. There are the functions coded:

def f(x):
    return x**2 - 4

def h(x):
    return (x-(((3-x)*f(x))/(f(3)-f(x))))

and now I would like to code the recursive sequence and print n first values of it:

xn+1 = h(xn)

For x1 = 4/3

My code isn't working of course (I receive the same value n times but I would like to get something alike):

def g(n):
    for i in range(1, n+1):
        x = 4/3
        x = h(x)
        print(x)

Upvotes: 3

Views: 276

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You simply overwrite x with 4/3 each iteration:

def g(n):
    for i in range(1, n+1):
        x = 4/3
        x = h(x)
        print(x)

Simply move the statement above the loop:

def g(n):
    x = 4/3
    for i in range(1, n+1):
        x = h(x)
        print(x)

Perhaps you also want to print(x) before you enter the loop.

Nevertheless, you can improve your code on some points: first of all I would not print the result: printing has side-effects. In a program you usually try to make a distinction between functions that calculate and functions that have side-effects.

Next and in the same context, I would use a generator an not return a list or something. You can simply define the sequence for an arbitrary amount of indices:

def g():
    x = 4/3
    while True:
        x = h(x)
        yield x

Now you can ask g for for instance the first 10 elements, or perform filters, ... Elements are furthermore generated lazily.

Upvotes: 4

Related Questions