通过组合尽可能多的免费符号来优化 sympy 表达式评估
想象一下,我有一个未知的、非常复杂的表达式,我需要重复地进行数值计算,例如:
my_expr = (a*b*c**2 - 2*sqrt(d*(a*b-c-e+x)))/(b - 1)
每次我重新计算表达式时,唯一改变的符号是“x”,因此对我来说预先计算所有其他符号是有意义的(我将最终使用 C 代码生成)。
所以我想要的是提前自动拉出并组合尽可能多的自由符号,除了x。这有点像 cse,但使最终表达式包含尽可能少的计算。
例如,对于上述情况,我最终可能会得到一个与此等效的系统:
var1 = a*b*c**2
var2 = a*b-c-e
var3 = b - 1
my_new_expr = (var1-2*sqrt(d*(var2+x)))/var3
这意味着我可以预先计算 var1,var2 & var3,并且重复计算(my_new_expr)在计算上尽可能简单。
无论如何,我可以以同情的方式做到这一点吗?我已经查看了所有简化方法等,包括收集等,但没有一个完全满足我的需要。如果做不到这一点,是否可以遍历表达式来实现此目的?
Imagine I have an unknown, quite complex expression that I need to repeatedly evaluate numerically, e.g.:
my_expr = (a*b*c**2 - 2*sqrt(d*(a*b-c-e+x)))/(b - 1)
Each time I reevaluate the expression, the only symbol that changes is 'x', so it makes sense for me to precompute all the others (I will be using c code generation eventually).
So what I want is to automatically pull out and combine as many free symbols as possible in advance, except for x. This would work a bit like cse, but making the final expression contain as few calculations as possible.
e.g. for the above I might end up with a system equivalent to this:
var1 = a*b*c**2
var2 = a*b-c-e
var3 = b - 1
my_new_expr = (var1-2*sqrt(d*(var2+x)))/var3
This means I can precalculate var1,var2 & var3, and the repeated calculation (my_new_expr) is as simple as possible computationally.
Is there anyway I can do this in sympy? I've looked through all the simplification methods etc, including collect etc, and none quite do what I need. Failing that, is there any traversal of the expression I could do to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然我在 sympy/smichr 的 model 分支有一个更全面的解决方案,但以下内容在压缩那些恒定的子表达式方面会做得很好:
Although my
model
branch at sympy/smichr has a more comprehensive solution, the following will do pretty well at condensing those sub-expressions that are constant: