#7742: add a compose function to sage
------------------------------------------------+---------------------------
Reporter: was | Owner: AlexGhitza
Type: enhancement | Status: needs_review
Priority: major | Milestone: sage-4.7
Component: misc | Keywords:
Author: Christopher Olah, Felix Lawrence | Upstream: N/A
Reviewer: Paul Zimmermann | Merged:
Work_issues: check argument type |
------------------------------------------------+---------------------------
Changes (by flawrence):
* status: needs_work => needs_review
Old description:
> {{{
>
> 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
>
> }}}
> To the release manager: apply only the last patch
> (trac_7742-add-compose-etc_v2_rebased.patch).
New description:
{{{
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
}}}
To the release manager: apply only the last patch
(trac_7742-add-compose-etc_v2.1.patch).
--
Comment:
Replying to [comment:39 zimmerma]:
> a minor point: it would be good to check that n is indeed a nonnegative
integer in
> {{{self_compose}}} and {{{nest}}}, otherwise we can get strange results
Done:
{{{
sage: self_compose(sin, -3)
...
ValueError: n must be a nonnegative integer, not -3.
sage: self_compose(sin, x)
...
TypeError: n (=x) must be of type (<type 'int'>, <type 'long'>, <type
'sage.rings.integer.Integer'>).
}}}
--
Ticket URL: <http://trac.sagemath.org/sage_trac/ticket/7742#comment:40>
Sage <http://www.sagemath.org>
Sage: Creating a Viable Open Source Alternative to Magma, Maple, Mathematica,
and MATLAB
--
You received this message because you are subscribed to the Google Groups
"sage-trac" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sage-trac?hl=en.