On Sat, Dec 19, 2009 at 11:53 AM, Robert Bradshaw
<rober...@math.washington.edu> wrote:
> On Dec 19, 2009, at 11:14 AM, Christopher Olah wrote:
>
>> Greetings!
>>
>> I can't seem to figure out how (elegantly) to make a function that is
>> the repeated composite of another. eg. Suppose I have a function f,
>> how do I get f*f*f*f...
>>
>> In math, I could just f^n,
>
> One difficulty with supporting that would be that it's bit ambiguous
> as powering is also often used for powering after application, not
> only repeated application (e.g. sin^2(x) is usually interpreted as
> (sin(x))^2) and it would make the gulf between functions and
> expressions even bigger.
>
> sage: f(x) = sin(x)
> sage: f^2
> x |--> sin(x)^2
> sage: f = sin(x)
> sage: f^2
> sin(x)^2
>
>> in normal lambda calculus, I'd just use n.f
>> (church numeral), but in sage the only way I could come up with was
>> using a loop to generate "f(f(...(x)))" and then printing it and copy
>> pasting it to the end of "g=lambda x: " and using that (and even then,
>> when I used ~100 iterations, sage crashed). There's got to be a more
>> elegant way...
>
> Though it's not perfect, you could do
>
> sage: def compose(f, n, x): return x if n == 0 else compose(f, n-1,
> f(x))
> ....:

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


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