Hi Andrew!

On 24 Aug., 15:35, andrew ewart <aewartma...@googlemail.com> wrote:
> suppose we define a function f(x)=x^3+1
> and define a_0=1
> and then had the iteration a_n=f(a_n-1)/(a_n-1)
> how would one go about writing this in sage?

You can use the fact that Sage is built on Python.

So, you can define a Python iterator, like that:
sage: def F(f,a0):
....:     an = a0
....:     while(1):
....:         yield an
....:         an = f(an)/an
....:

Since the function uses "yield" rather than return, calling F with two
arguments is an iterator.

You want a function x->x^3+1 and a starting value, say, 1.0 (I use
floating points; if you start with "1" instead of "1.0", all return
values will be rational, not floating point).

# The function:
sage: f = lambda x: x^3+1
# the iterator:
sage: L = F(f,1.0)
sage: for i in range(10): # iterate over the first ten values
....:     print L.next()
....:
1.00000000000000
2.00000000000000
4.50000000000000
20.4722222222222
419.160729391762
175695.719449953
3.08689858330367e10
9.52894286360222e20
9.08007520977956e41
8.24477658152533e83

You could also do "for x in L: print x". In theory, you'd get an
infinite loop, but since the starting value was a float, it will soon
yield an error as the numbers are too big.

Cheers,
Simon

-- 
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