我输入了大量的数学表达式和方程式,我想打印出各自的乳胶表示.到目前为止,我已经尝试过Sage和sympy,但棘手的部分是不对表达式中的术语进行重新排序.
所以,如果我的输入是这样的话,可以eval在python中使用-ed:
(C - A*x) / B
Run Code Online (Sandbox Code Playgroud)
我想要的输出将是这样的:
\frac{C - A x}{B}
Run Code Online (Sandbox Code Playgroud)
我不想要的是这样的:
\frac{-(A x - C)}{B}
\frac{1}{B}(C - A x)
etc...
Run Code Online (Sandbox Code Playgroud)
这可以实现吗?我慢慢失去希望......
编辑:
输入表达式是多样的,一些包含平方根,嵌套括号,指数等.寻找通用解决方案.
到目前为止,这是不起作用的:
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}
Run Code Online (Sandbox Code Playgroud)
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)'
Run Code Online (Sandbox Code Playgroud)
\您可以通过创建实现标准Python数据模型的Symbol和Operator类来做到这一点(http://docs.python.org/2/reference/datamodel.html)。尽管您可以通过括号重新排列,但这将使事情保持与 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')
Run Code Online (Sandbox Code Playgroud)
然后:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
369 次 |
| 最近记录: |