Sympy 不会评估 2x 但会评估 x*2
我正在使用 Sympy 的 sympify 函数来简化 2 个表达式,以便我可以比较它们是否相等。
例如:
expr1 = sympify("(2 * x) + (x + 10)")
expr2 = sympify("(x + 10) + (x * 2)")
if expr1 == expr2:
print "Congrats those are essentially the same!"
但是,当使用 2x 形式与 x*2 相对时,我会得到解析异常,例如:
expr1 = sympify("2x + (x + 10)")
有什么方法可以让我理解 2x 形式?
如果没有,是否有其他图书馆允许这种形式?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您可以修改 sympy 词法分析器(或解析器/语法/其他)。
您还可以使用一个为您转换输入字符串的函数来包装它,使用如下所示的内容:
但是问问自己为什么一开始不存在这种符号。
例如,所有这些都是有效的 python,虽然自从我搞乱 sympy 以来已经有一段时间了,但我敢打赌它们除了 sympy 中的乘法之外还有其他含义:
那么
x2
是什么意思?它是一个名为x2
的变量还是它的意思是(x * 2)
。我故意将这种情况排除在上面的正则表达式之外,因为它非常模糊。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:
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:
And what does
x2
mean? Is it a variable namedx2
or does it mean(x * 2)
. I purposely left this case out of the regular expression above because it's so ambiguous.SymPy 的开发版本具有解析此类表达式的能力。请参阅 http://docs.sympy.org/dev/modules/解析#sympy.parsing.sympy_parser.implicit_multiplication_application。默认情况下,
sympify
中仍然未启用它,因为sympify
仅对 Python 语法进行非常基本的扩展(即,包装数字文字和未定义的名称,以及转换>^
到**
)。但那里有一个例子展示了如何使用它。请注意,这目前也适用于隐式函数应用。也许这两个功能应该分开。
编辑:这些函数正在 拉取请求 中拆分。
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
, becausesympify
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.