Reputation: 1173
I have been using SymPy to convert expressions into latex (to then be rendered by Matplotlib). e.g.
from sympy import latex, sympify
from sympy.abc import x
str = '2*x + 3*x'
TeX = latex(sympify(str))
The problem is that it automatically processes the expression, so 2*x + 3*x automatically becomes 5*x etc; which is not what I want (don't ask!).
Upvotes: 4
Views: 1717
Reputation: 421
>>> import re
>>> re.sub("(^|[\(\[\{\+\-\*/ ,\:=])(\-?[0-9]*\.?[0-9]+)", "\\1Dummy('\\2')", '2*x + 3*x')
"Dummy('2')*x + Dummy('3')*x"
>>> eval(_)
2⋅x + 3⋅x
>>> latex(_)
'2 x + 3 x'
Upvotes: -1
Reputation: 3020
Actually when you call sympify(str) it tries to parse expression and convert them into the default classes. In this case Add(2*x,2*x)
will be called (with default parameter evalaute=True) so this became 5*x
. If you want to avoid it either you have to call Add(2*x,3*x,evaluate=False)
or use some global variable and check in init method of AssocOp class in core-> operation.py
i am doing this
try:
import __builtin__
evaluate_expr=__builtin__.evaluate_expr
except AttributeError ,ex:
pass
if ((not options.pop('evaluate', True)) or (evaluate_expr==False)) :
**Note - sympy use caching for function , so if you call same function (say :sympy("2*x+3*x")
)two times .1st time with your gloabl variable evalute=True
and 2nd time with evaluate=False
. in both cases becuase of caching you will get same result.
So you need to update methods like (add ,mul ) in core->expr class. something like below
def __add__(self, other):
#simplifychange:
evaluate_expr=self.get_evaluate()
return Add(self, other,evaluate=evaluate_expr)
But i will suggest it would be better if you dont use evaluate=False. Behavior of sympy will change dramatically. problems like i was facing in this post
Upvotes: 1
Reputation: 14420
Sympy's Add
class handles the addition of symbols. You can provide a keyword argument to stop the automatic collection of terms.
from sympy import Add
from sympy.abc import x
eq = Add(2*x, 3*x, evaluate=False)
# this will print: 2*x + 3*x
print eq
This may not be exactly what you want based on your reply to phimuemue's comment.
Upvotes: 6