Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy won't evaluate 2x but will evaluate x*2

Tags:

python

math

sympy

I'm using Sympy's sympify function to simplify 2 expressions so I can compare them for equality.

For example:

expr1 = sympify("(2 * x) + (x + 10)")
expr2 = sympify("(x + 10) + (x * 2)")

if expr1 == expr2:
   print "Congrats those are essentially the same!"

However when using the form 2x as apposed to x*2 i get a parse exception eg:

expr1 = sympify("2x + (x + 10)")

Is there any way I can get sympy to understand the 2x form ?

If not, is there any other library that will allow this form ?

like image 549
sleepyjames Avatar asked Feb 23 '11 00:02

sleepyjames


2 Answers

Well, you could modify the sympy lexer (or parser / grammar / whatever).

You could also wrap it with a function that transformed your input strings for you, using something like this:

>>> import re
>>> expr = '2x + 1'
>>> re.sub(r"(\d+)(\w+)", r"(\1 * \2)", expr)
'(2 * x) + 1'

But ask yourself why this notation isn't there to begin with.

For example, all of these are valid python, and though it's been a long while since I messed with sympy, I bet they mean something besides multiplication in sympy too:

0x32  # hex for 50
5e-3  # 0.005
2j    # 2 * sqrt(-1) (so that one *is* multiplication, but by 1j, not j!)
15L   # 15 (L used to represent long integers in python)

And what does x2 mean? Is it a variable named x2 or does it mean (x * 2). I purposely left this case out of the regular expression above because it's so ambiguous.

like image 58
tangentstorm Avatar answered Nov 18 '22 13:11

tangentstorm


The development version of SymPy has the ability to parse such expressions. See http://docs.sympy.org/dev/modules/parsing#sympy.parsing.sympy_parser.implicit_multiplication_application. It is still not enabled by default in sympify, because sympify only does very basic extensions to the Python syntax (i.e., wrapping of numeric literals and undefined names, and converting ^ to **). But there is an example there that shows how to use it.

Note that this currently also applies implicit function application as well. Probably the two functionalities should be split up.

EDIT: Those functions are being split up in a pull request.

like image 2
asmeurer Avatar answered Nov 18 '22 14:11

asmeurer