替代sympy,无需评估或简化表达式

编程入门 行业动态 更新时间:2024-10-27 23:21:14
本文介绍了替代sympy,无需评估或简化表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下示例:

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).

推荐答案

使用 UnevaluatedExpr(5)而不是5:

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

此包装器防止其内部的表达式("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,无需评估或简化表达式

本文发布于:2023-06-05 01:22:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/508960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   sympy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!