Ask Your Question
1

Is there a shortcut command to iterate an endomorphism?

asked 2020-12-01 05:08:08 +0100

vikahdv@gmail.com gravatar image

updated 2020-12-01 05:30:50 +0100

slelievre gravatar image

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 flag offensive close merge delete

Comments

Welcome to Ask Sage!

Thank you for your question.

slelievre gravatar imageslelievre ( 2020-12-01 05:19:33 +0100 )edit

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

slelievre gravatar imageslelievre ( 2020-12-01 05:20:16 +0100 )edit
slelievre gravatar imageslelievre ( 2020-12-01 05:32:28 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2020-12-10 16:29:03 +0100

Sylvain gravatar image

updated 2020-12-12 23:12:17 +0100

slelievre gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-12-01 05:08:08 +0100

Seen: 248 times

Last updated: Dec 12 '20