7

我输入了大量的数学表达式和方程式,我想为它们打印出乳胶表示。到目前为止,我已经尝试过 Sage 和 sympy,但棘手的部分是不对表达式中的术语进行重新排序。

因此,如果我的输入是这样的,那么可以eval在 python 中进行编辑:

(C - A*x) / B

我想要这样的输出:

\frac{C - A x}{B}

想要的是这样的:

\frac{-(A x - C)}{B}
\frac{1}{B}(C - A x)
etc...

这可以实现吗?我正在慢慢失去希望...


编辑:

输入表达式多种多样,有些包含平方根、嵌套括号、指数等。寻找通用解决方案。

到目前为止,这是行不通的:

1)鼠尾草:

sage: var('A B C x y') 
(A, B, C, x, y) 
sage: latex(y == (C - A*x) / B)
y = -\frac{A x - C}{B}

2)同情:

>>> from sympy import *
>>> x = Symbol('x')
>>> A = Symbol('A')
>>> B = Symbol('B')
>>> C = Symbol('C')
>>> latex((C - A*x) / B)
'\\frac{1}{B} \\left(- A x + C\\right)'
4

2 回答 2

3

除了编写自己的解析器之外,我相信唯一真正的方法是使用python 的内置compile()函数并处理返回的抽象语法树。

于 2013-10-30T21:52:04.027 回答
1

\您可以通过创建实现标准 python 数据模型 ( http://docs.python.org/2/reference/datamodel.html ) 的 Symbol 和 Operator 类来做到这一点。这将使事情保持与 python 运算符优先级相同的顺序,尽管您可以通过括号重新排列:

class Symbol(object):
    def __init__(self, name):
        self._name = name

    def __str__(self):
        return str(self._name)

    def __div__(self, other):
        return Div(self, other)

    def __mul__(self, other):
        return Mult(self, other)

    def __add__(self, other):
        return Add(self, other)

    def __sub__(self, other):
        return Sub(self, other)

    def __rdiv__(self, other):
        return Div(other, self)

    def __rmul__(self, other):
        return Mult(other, self)

    def __radd__(self, other):
        return Add(other, self)

    def __rsub__(self, other):
        return Sub(other, self)

class Operation(Symbol):
    def __init__(self, a, b, op):
        self._a = a
        self._b = b
        self._op = op

    def __str__(self):
        return self._op.format(self._a, self._b)

class Add(Operation):
    precedence = 0

    def __init__(self, a, b):
        super(Add, self).__init__(a, b, "{0} + {1}")

class Sub(Operation):
    precedence = 0
    def __init__(self, a, b):
        super(Sub, self).__init__(a, b, "{0} - {1}")

class Mult(Operation):
    precedence = 1
    def __init__(self, a, b):
        if isinstance(a, Operation) and a.precedence < Mult.precedence:
            a_form = "({0})"
        else:
            a_form = "{0}"
        if isinstance(b, Operation) and b.precedence < Mult.precedence:
            b_form = "({1})"
        else:
            b_form = "{1}"
        super(Mult, self).__init__(a, b, a_form + " " + b_form)

class Div(Operation):
    precedence = 1
    def __init__(self, a, b):
        super(Div, self).__init__(a, b, "\\frac{{{0}}}{{{1}}}")


A = Symbol('A')
B = Symbol('B')
C = Symbol('C')
x = Symbol('x')

然后:

>>> print (C - A * x) / (B)
\frac{C - A x}{B}
>>> print (C * (A + B))
C (A + B)
>>> print (C * (A + B + A + B + C + x))
C (A + B + A + B + C + x)
于 2013-10-30T21:24:43.027 回答