替代sympy,无需评估或简化表达式 [英] Substitute in sympy wihout evaluating or simplifying the expression
问题描述
考虑以下示例:
from sympy import *
x = Symbol('x')
f = sqrt(3*x + 2)
现在我想用数字代替,例如用 5
代替 x
并获得LaTeX表示,在这种情况下,它应该返回
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)
我该怎么做?
我尝试了 latex(f.subs(x,2,evaluate = False))
,但是结果只出现在 \\ sqrt(17)
中.
I tried latex(f.subs(x,2,evaluate=False))
but this results just in \\sqrt(17)
.
推荐答案
使用此包装器防止其内部的表达式("5")与外部术语进行交互.参考:防止表达式评估
This wrapper prevents the expression inside of it ("5") from interacting with the outside terms. Reference: Prevent expression evaluation
替换后加数的顺序不同,因为 3 * x + 2
和 3 * 5 + 2
由打印机进行不同的排序.为了避免这种情况,可以使用 order ='none'
保持参数的内部顺序,而不必尝试将其置于人性化的位置.
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}'
这篇关于替代sympy,无需评估或简化表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!