i'm using 64-bit python 3.3.1, pylab , 32gb system ram. function:
def sqrt2expansion(limit): x = symbol('x') term = 1+1/x _ in range(limit): term = term.subs({x: (2+1/x)}) return term.subs({x: 2}) produces expressions of kind: 1 + 1/(2 + 1/(2 + 1/(2 + 1/(2 + 1/(2 + 1/(...)))))). when called as: sqrt2expansion(100) returns valid result, sqrt2expansion(200) produces runtimeerror many pages of traceback , hangs pylab/ipython interpreter plenty of system memory left unused. ideas how implement more efficiently? call sqrt2expansion(1000) , still result.
i try elaborate on comment have posted above.
sympy expressions trees. each operation node has branches operands. instance x+y looks add(x, y) , x*(y+z) mul(x, add(y, z)).
usually these expressions automatically flattened in add(x, add(y, z)) becoming add(x, y, z), more complicated cases 1 can deep trees.
and deep trees can pose problems when either interpreter or library limits depth of permitted recursion (as protection against infinite recursion , exploding memory usage). cause of runtimeerror: each subs makes tree deeper , tree gets deeper recursive subs must call more times till gets deepest node.
you can simplify tree of form polynomial/polynomial has constant depth using factor method. change term = term.subs({x: (2+1/x)}) term = term.subs({x: (2+1/x)}).factor().
Comments
Post a Comment