Ask Your Question
1

Is there a shortcut command to iterate an endomorphism?

asked 2020-11-30 22:08:08 -0600

updated 2020-11-30 22:30:50 -0600

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-11-30 22:19:33 -0600 )edit

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

slelievre gravatar imageslelievre ( 2020-11-30 22:20:16 -0600 )edit
slelievre gravatar imageslelievre ( 2020-11-30 22:32:28 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2020-12-10 09:29:03 -0600

Sylvain gravatar image

updated 2020-12-12 16:12:17 -0600

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-11-30 22:08:08 -0600

Seen: 78 times

Last updated: Dec 12 '20