Substitute in sympy wihout evaluating or simplifying the expression

拜拜、爱过 提交于 2021-02-10 18:04:04

问题


Consider the follwing example:

from sympy import *
x = Symbol('x')
f = sqrt(3*x + 2)

Now I want to substitute a number, say 5 for x and get a LaTeX represenation, in this case it should return

\\sqrt(3\\cdot 5 + 2)

How can I do this?

I tried latex(f.subs(x,2,evaluate=False)) but this results just in \\sqrt(17).


回答1:


Use UnevaluatedExpr(5) instead of 5:

>>> latex(f.subs(x, UnevaluatedExpr(5)))
'\\sqrt{2 + 3 \\cdot 5}'

This wrapper prevents the expression inside of it ("5") from interacting with the outside terms. Reference: Prevent expression evaluation


The order of addends isn't the same after substitution, as 3*x + 2 and 3*5 + 2 get sorted differently by the printer. To avoid this, one can use order='none' which keeps whatever internal order the arguments have, without trying to put them in a human-friendly arrangement.

>>> latex(f, order='none')
'\\sqrt{2 + 3 x}'
>>> latex(f.subs(x, UnevaluatedExpr(5)), order='none')
'\\sqrt{2 + 3 \\cdot 5}'


来源:https://stackoverflow.com/questions/49842196/substitute-in-sympy-wihout-evaluating-or-simplifying-the-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!