Is it possible to prevent recursion or eval

16 views
Skip to first unread message

bsdz

unread,
Aug 28, 2015, 9:22:30 AM8/28/15
to sympy
Hi

I'm looking at Lucas Lehmer sequences. I am modelling them in Sympy.

I've created a function class:

class L(Function):
    nargs
= (1)

    _recursions_maximum
= S.Infinity
    _recursions_count
= 0

   
@classmethod
   
def set_recursion_count(cls, c):
        cls
._recursions_maximum = c
        cls
._recursions_count = 0

   
@classmethod
   
def eval(cls, x):
        cls
._recursions_count += 1
       
if cls._recursions_count > cls._recursions_maximum:
            cls
._recursions_maximum = S.Infinity
           
return
       
elif x is S.Zero:
           
return 4
       
else:
           
return (L(x-1)**2)-2

This does work mostly as expected although I am running into trouble with the sympy cache:

n = Symbol('n', integer=True, positive=True)
L
.set_recursion_count(2)
print(L(n))
>> (L(n - 2)**2 - 2)**2 - 2

print(L(4))
>> 1416317954

clear_cache
()
L
.set_recursion_count(2)
print(L(4))
>> (L(2)**2 - 2)**2 - 2


The first two outputs (highlighted with >>) are expected but the fourth must be cached from somewhere?

Is there a better way to do this? Ideally, I'd like to avoid adding the maximum recursion limit as an argument to my function.

Thanks in advance!

Reply all
Reply to author
Forward
0 new messages