是否有优化表达式的算法?

时间:2013-05-12 00:56:20

标签: algorithm optimization expression

例如,我有表达式数组 x + 2 *(4 * 7)

{ "x" , "+" , "2" , "*" , "(" , "4" , "*" , "7" , ")" }

我需要获得 x + 56 之类的输出。这是一个简单的例子,可能会困难得多。我知道Dijkstra的调车场算法,但不确定这是否可以帮助专门进行优化。坦率地说,我不知道如何理解表达式最大化优化,因为我看不到所有可能的优化方法。也许有一种算法可以考虑所有细微差别?

2 个答案:

答案 0 :(得分:2)

在您的问题中,用于优化表达式的技术称为constant folding。它找到表达式,其中每个值都是常量,并用操作的结果替换该表达式。

Start with x+2*(4*7)
Notice 4*7 is an operation with constant arguments
Compute 4*7=28, replace in expression to get x+2*(28)
Notice (28) can be de-bracketed, to get x+2*28
Notice 2*28 is an operation with constant arguments
Compute 2*28=56, replace in expression to get x+56
Notice there are no more operations with all constant arguments
End with x+56

另见:

答案 1 :(得分:0)

您可能正在寻找的是computer algebra system。有several open source systems可用;如果您将使用限制为每月几千次api通话,您也可以免费使用Wolfram Alpha API