使用 sympy 和 PythonTex 更改分数的打印格式

Changing printing format for fractions using sympy and PythonTex

下面是我正在处理的一个最小的工作问题。 该文件是在 pythontex 中使用 sympy 的标准 LaTeX 文件,我想在其中更改 sympy 如何显示分数。

具体我想做以下修改,但是一直在纠结:

下面我附上了两张图片,显示了我的代码生成的内容以及我希望它显示的内容。请注意,这在上面的两个项目符号中也有说明

当前输出

期望的输出

代码

\documentclass{article}
\usepackage{pythontex}
\usepackage{mathtools,amssymb}
\usepackage{amsmath}
\usepackage{enumitem}

\begin{document}

\begin{pycode}
import math
from sympy import *
from random import randint, seed

seed(2021)
\end{pycode}

\paragraph{Oppgave 3}

\begin{pycode}
a, b = randint(1,2), 3
ab = Rational(a,b)

pressure_num = lambda x: 1-x
pressure_denom = lambda x: 1+x

def pressure(x):
  return (1-x)/(1+x)

pressure_ab = Rational(pressure_num(ab),pressure_denom(ab))

x, y, z = symbols('x y z')
pressure_derivative = simplify(diff(pressure(x), x))
pressure_derivative_ab = pressure_derivative.xreplace({ x : Rational(a,b)}) 
\end{pycode}

The partial pressure of some reaction is given as
%
\begin{pycode}
print(r"\begin{align*}")
print(r"\rho(\zeta)")
print(r"=")
print(latex(pressure(Symbol('\zeta'))))
print(r"\qquad \text{for} \ 0 \leq \zeta \leq 1.")
print(r"\end{align*}")
\end{pycode}
%
\begin{enumerate}[label=\alph*)]
    \item Evaluate $\rho(\py{a}/\py{b})$. Give a physical interpretation of your
        answer.
    \begin{equation*}
        \rho(\py{a}/\py{b})
        = \frac{1-(\py{ab})}{1+\py{ab}}
        = \frac{\py{pressure_num(ab)}}{\py{pressure_denom(ab)}}
        \cdot \frac{\py{b}}{\py{b}}
        = \py{pressure_ab}
    \end{equation*}
\end{enumerate}

The derivative is given as
%
\begin{pycode}
print(r"\begin{align*}")
print(r"\rho'({})".format(ab))
print(r"=")
print(latex(pressure_derivative))
print(r"=")
print(latex(simplify(pressure_derivative_ab)))
print(r"\end{align*}")
\end{pycode}

\end{document}

Whenever I substitute this expression into the fraction it fully simplifies the expression, which is not what I want. I just want to replace x with the fraction a/b (in this case 2/3 or 1/3 depending on the seed).

可以这样做,如果我们用with表达式来表示temporarily disable evaluation for that code block, and then we use two dummy variables来表示分数,最后我们用数值代入。

因此您的代码中的以下行:

pressure_derivative_ab = pressure_derivative.xreplace({ x : Rational(a,b)}) 

可改为:

with evaluate(False):
    a1,b1=Dummy('a'),Dummy('b')
    pressure_derivative_ab = pressure_derivative.subs(x,a1/b1).subs({a1: a,b1: b})

这之后的表达式pressure_derivativepressure_derivative_ab是:

How can I make sympy display the full, and not inline version of it's fractions for some of its fractions? In particular I would like the last fraction 1/5 to instead be displayed in full. eg. \fraction{1}{5}

为此,您只需更改这一行:

        = \py{pressure_ab}

进入这一行:

        = \py{latex(pressure_ab)}

因为我们希望 pythontex 使用 sympy latex printer, instead of the ascii printer.

总而言之,原始代码和修改后的代码之间的变化可以是viewed here

这个post中的所有代码都是also available in this repo