You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让SymPy的print_latex保持原始分式形式,避免自动转换?

Solution

SymPy automatically rationalizes denominators and simplifies expressions by default, which is why your initial code produces the combined fraction. To retain the original form in LaTeX output, you need to prevent this evaluation. Here are two effective methods:

Method 1: Use the evaluate context manager

Wrap your expression creation in a with evaluate(False): block to disable automatic simplification:

from sympy import *
x = symbols('x')

with evaluate(False):
    y = (1 / sqrt(2)) * cos(x)

print_latex(y)

This will output:

\frac{1}{\sqrt{2}} \cos{\left(x \right)}

Method 2: Use UnevaluatedExpr for the fractional term

Wrap the numerator and denominator of your fraction in UnevaluatedExpr to preserve the division as written:

from sympy import *
x = symbols('x')

inv_sqrt2 = UnevaluatedExpr(1) / UnevaluatedExpr(sqrt(2))
y = inv_sqrt2 * cos(x)

print_latex(y)

This also produces the desired LaTeX output.

Why your previous attempt didn't work

When you used Mul(1/(sqrt(2)), cos(x), evaluate=False), the division 1/(sqrt(2)) had already been simplified to sqrt(2)/2 before the multiplication was created. The evaluate=False flag only affects the multiplication operation, not the prior division.

内容的提问来源于stack exchange,提问作者quark67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:47:33