使用64位的Python 3.3.1和32GB的RAM和該功能可以生成目標表達1+1/(2+1/(2+1/...))
:Python的內存錯誤sympy.simplify
def sqrt2Expansion(limit):
term = "1+1/2"
for _ in range(limit):
i = term.rfind('2')
term = term[:i] + '(2+1/2)' + term[i+1:]
return term
打電話時我得到MemoryError
:
simplify(sqrt2Expansion(100))
較短的表情做工精細,如:
simplify(sqrt2Expansion(50))
有沒有辦法來CONF用SymPy來完成這個計算?以下是錯誤消息:
MemoryError Traceback (most recent call last)
<ipython-input-90-07c1e2de29d1> in <module>()
----> 1 simplify(sqrt2Expansion(100))
C:\Python33\lib\site-packages\sympy\simplify\simplify.py in simplify(expr, ratio, measure)
2878 from sympy.functions.special.bessel import BesselBase
2879
-> 2880 original_expr = expr = sympify(expr)
2881
2882 expr = signsimp(expr)
C:\Python33\lib\site-packages\sympy\core\sympify.py in sympify(a, locals, convert_xor, strict, rational)
176 try:
177 a = a.replace('\n', '')
--> 178 expr = parse_expr(a, locals or {}, rational, convert_xor)
179 except (TokenError, SyntaxError):
180 raise SympifyError('could not parse %r' % a)
C:\Python33\lib\site-packages\sympy\parsing\sympy_parser.py in parse_expr(s, local_dict, rationalize, convert_xor)
161
162 code = _transform(s.strip(), local_dict, global_dict, rationalize, convert_xor)
--> 163 expr = eval(code, global_dict, local_dict) # take local objects in preference
164
165 if not hit:
MemoryError:
編輯:
我寫了使用sympy表達式不是字符串的一個版本:
def sqrt2Expansion(limit):
x = Symbol('x')
term = 1+1/x
for _ in range(limit):
term = term.subs({x: (2+1/x)})
return term.subs({x: 2})
它運行好:sqrt2Expansion(100)
返回有效的結果,但sqrt2Expansion(200)
產生了帶有許多追溯頁面的RuntimeError
,並掛起IPython解釋器,留下大量未使用的系統內存。我用這個問題創建了新的問題Long expression crashes SymPy。
你能粘貼錯誤輸出嗎? – donfede 2013-05-05 10:01:54
你可以直接用數學表達式寫出這個字符串,你不應該使用字符串。 – Krastanov 2013-05-05 12:58:15
@Krastanov我會試試,謝謝。 – 2013-05-05 17:41:44