如何让SymPy的print_latex保持原始分式形式,避免自动转换?
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

