# Revision history [back]

In the next version of sage (4.7) you will be able to use the functions self_compose and nest to do this. Use nest when you want to find $f(f(...f(x)...))$ for known $x$, and use self_compose when you want a function that has not been evaluated.

In the meantime you'll need to define them yourself:

def nest(f, n, x):
"""Return f(f(...f(x)...)), where the composition occurs n times."""
for i in xrange(n):
x = f(x)
return x

def self_compose(f, n):
"""Return the function f composed with itself n times."""
return lambda x: nest(f, n, x)


For usage examples and more documentation, see the patch that adds this functionality.

In the next version of sage (4.7) you will be able to use the functions self_compose and nest to do this. Use nest when you want to find $f(f(...f(x)...))$ for known $x$, and use self_compose when you want a function that has not been evaluated.

In the meantime you'll need to define them yourself:

def nest(f, n, x):
"""Return f(f(...f(x)...)), where the composition occurs n times."""
for i in xrange(n):
x = f(x)
return x

def self_compose(f, n):
"""Return the function f composed with itself n times."""
return lambda x: nest(f, n, x)


For usage examples and more documentation, see the patch that adds this functionality.functionality. There is one example which is very similar to yours:

    sage: def f(x): return x^2 + 1
sage: x = var('x')
sage: nest(f, 3, x)
((x^2 + 1)^2 + 1)^2 + 1