Limit comparison test

asked 2022-09-21 18:40:12 +0200

jaema gravatar image

Hi! I want to define a function to do limit comparison test. I want the function that can be given one or three arguments. First argument should be the formula for n-th element of sequence I want to put to the test - a. Second, optional, argument should be the formula for n-th element of sequence I want to compare with - b. Third argument should be the letters 'k' or 'd' wether the given sequence b is convergent or divergent.

I have problem to define a function with optional number of arguments. I don't know how to make the program differentiate the number of arguments. I used the nargs command but it does not work.

var('n,b,L')
def limzk(a, *args):  
if nargs==0:
    b=1/n^2
    L=lim(a/b, n=Infinity)
    if L<Infinity:
        print('convergent')
    else:
        b=1/n
        L=lim(a/b, n=Infinity)
        if L>0:
            print('divergent')
        else:
            print('cannot be decided by this test')
elif nargs==2:
    if args[1]==('k'):
        b=args[0]
        L=lim(a/b, n=Infinity)
        if L<Infinity:
            print('convergent')
        else:
            print('cannot be decided by this test')
    elif args[1]==('d'):
        b=args[0]
        L=lim(a/b, n=Infinity)
        if L>0:
            print('divergent')
        else:
            print('cannot be decided by this test')
else:
    print('ERROR: wrong number of parameters given')

Thank you for help.

edit retag flag offensive close merge delete

Comments

Your problem seems to be the use of arguments in a Python function rather than Sage-specific. A few notes :

  • Your code defines b and L variables local to limzk ; globals b and L won't be used by this code.

  • Are you sanguine about the order of your arguments ?

  • What about keyword arguments ?

  • Why distinct behaviour for the no-argument case (which returns either "convergent","divergent" or "undecidable") and the two-arguments case ?

  • the catchall print("ERROR"...) code would be avanteageously replaced by raising an exception. Or, even better,

  • you could enclose the body of your code in a try...except statement.

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2022-09-23 17:20:05 +0200 )edit