# Is there a shortcut command to iterate an endomorphism?

Suppose $f$ is a function from some set to itself. Is there a shortcut command in sage to compute an iterated composition of $f$, such as $f^3(x)=f(f(f(x)))$ where I could type something like f^3(x) into the console, and more generally for computing $f^n(x)$ for a given $n$?

edit retag close merge delete

( 2020-12-01 05:19:33 +0200 )edit

Ideally, provide an explicit f, x, n to get others started on your question.

( 2020-12-01 05:20:16 +0200 )edit

Two previous related questions:

One keyword: dynamical systems.

( 2020-12-01 05:32:28 +0200 )edit

Sort by ยป oldest newest most voted

You can define a function that takes a function f and an integer n, and returns the n-th iterate of f.

This can be done using def and lambda:

sage: def iterate(f, n):
....:     r"""
....:     Return the n-th iterate of f.
....:     """
....:     if n not in NN:
....:         raise ValueError("can only define n-th iterate for n in NN")
....:     return lambda x: x if n == 0 else iterate(f, n-1)(f(x))


or using nested lambdas:

sage: iterate = lambda f, n: lambda x: x if n == 0 else iterate(f, n-1)(f(x))


Then, given a function, for instance:

sage: def square(x):
....:     return x**2


you can define its iterate:

sage: f = iterate(square, 4)
sage: f
<function ...>


and compute with it:

sage: f(x)
x^16


or directly:

sage: iterate(square, 4)(x)
x^16

more