> The following is better.   It is longer, but it will work even if n >=
> 1000, whereas the above will fail spectacularly due to Python's stack
> limit.  Also, the following is a bit faster than the above:
>
> def compose(f, n, a):
>    """
>    Return f(f(...f(a)...)), where the composition occurs n times.
>
>    INPUT:
>        - `f` -- anything that is callable
>        - `n` -- a nonnegative integer
>        - `a` -- any input for `f`
>
>    OUTPUT:
>        result of composing `f` with itself `n` times and applying to `a`.
>
>    EXAMPLES::
>
>        sage: def f(x): return x^2 + 1
>        sage: x = var('x')
>        sage: compose(f, 3, x)
>        ((x^2 + 1)^2 + 1)^2 + 1
>    """
>    n = Integer(n)
>    if n <= 0: return a
>    a = f(a)
>    for i in range(n-1): a = f(a)
>    return a

Two thoughts:

(1) For negative numbers, it should be the inverse function, if that
is feasible. Otherwise, an error.

(2) Secondly, could we get this to return a function, somehow? In the
present state, I imagine I could do something like:

sage: x=var('x')
sage: f = compose(sin, 10, x)
sage: f = lambda z : f(x=z)
#f= sin^10(x)

> I independently called mine "compose" too, so that must be the right name!
>
> I've made adding this to the library:
> http://trac.sagemath.org/sage_trac/ticket/7742
>
> I hope somebody will make a patch, etc. (since this would be good
> practice for somebody, and I have other things to do).
>
> William

-- 
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to