问题
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