Processing math: 100%

First time here? Check out the FAQ!

Ask Your Question
1

Is there a shortcut command to iterate an endomorphism?

asked 4 years ago

vikahdv@gmail.com gravatar image

updated 4 years ago

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 f3(x)=f(f(f(x))) where I could type something like f^3(x) into the console, and more generally for computing fn(x) for a given n?

Preview: (hide)

Comments

Welcome to Ask Sage!

Thank you for your question.

slelievre gravatar imageslelievre ( 4 years ago )

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

slelievre gravatar imageslelievre ( 4 years ago )

1 Answer

Sort by » oldest newest most voted
2

answered 4 years ago

Sylvain gravatar image

updated 4 years ago

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
Preview: (hide)
link

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: 4 years ago

Seen: 278 times

Last updated: Dec 12 '20