Ask Your Question
0

How to define a recursive sequence on Sage?

asked 2012-03-20 12:48:12 +0200

Ajat gravatar image

Hi, can someone tell me how to define a recurrence relation? I've tried this

def a(n):
if n==1:
        return 1
        else
              return a(n-1)+1/a(n-1)^2

It gives the following error:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "_sage_input_10.py", line 10, in <module>
        exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("ZGVmIGEobik6CiAgICBpZiBuPT0xOgogICAgICAgIHJldHVybiAxCiAgICAgICAgZWxzZQogICAgICAgIHJldHVybiBhKG4tMSkrMS9hKG4tMSleMg=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
      File "", line 1, in <module>

  File "/private/var/folders/u5/u5DFi45LFQ4s8DR+4Sy8NE+++TI/-Tmp-/tmpaYysvY/___code___.py", line 6
    else
       ^
SyntaxError: invalid syntax

thanks before.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2012-03-20 14:04:04 +0200

niles gravatar image

If you are looping over the values, you could also use an iterator:

def agen(max=Infinity):
    n = 1
    an = 1
    while n <= max:
        yield an
        n += 1
        an = (an + 1)/an^2

sage: a = agen(10)
sage: a.next()
1
sage: a.next()
2
sage: a.next()
3/4
sage: a.next()
28/9

The iterator will holds its place, and just return the next values:

sage: for i in a:
    print i.n()
....:     
0.424744897959184
7.89733878022166
0.142658807621492
56.1460737783674
0.0181279048720525
3098.18333611815

To start over, create a new instance:

sage: b = agen(20)
sage: for i in b:
    print i.n()
....:     
1.00000000000000
2.00000000000000
0.750000000000000
3.11111111111111
0.424744897959184
7.89733878022166
0.142658807621492
56.1460737783674
0.0181279048720525
3098.18333611815
0.000322873975252950
9.59564379989618e6
1.04213966781966e-7
9.20763703388443e13
1.08605497406118e-14
8.47805797477591e27
1.17951540668302e-28
7.18774670236615e55
1.39125659460260e-56
5.16637026573754e111
edit flag offensive delete link more
0

answered 2012-03-20 12:59:45 +0200

Shashank gravatar image

What you wrote works. You were just missing a colon after else.

def a(n):
    if n==1:
        return 1
    else:
        return a(n-1)+1/a(n-1)^2
edit flag offensive delete link more

Comments

oh my, thanks :)

Ajat gravatar imageAjat ( 2012-03-20 13:04:42 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-03-20 12:48:12 +0200

Seen: 6,379 times

Last updated: Mar 20 '12