2

I found these two libraries: - muparser - symbolicc++

The first one is capable of efficient parsing of mathematical expression, so that with minimal wrapping I could make a parser object so that

parser my_parser("1/2 * x^2");
cout<<myparser(2)<<endl;

Would result in it printing 2.0. This is wonderful, but it only works with doubles, right?

The second one implements the Symbolic object so that on example I can do something like:

Symbolic x("x");
Symbolic x2 = x^2;
cout<<df(x2, x)<<endl;

Resulting in 2.0*x. So it is capable of differentiating expressions, which is fine.

What I would need to do is a mix of the two! I need a function to be parsed and then differentiated, so that I could do something like:

 cout<<df("1/2 * x^2", "x")<<endl;

And I would like it to print out 2.0*x as well.

Is it possible to do something like this? In principle, if muparser could work on any object, I could simply run an expression on Symbolic objects, and then differentiate them. But I couldn't make something like this work.

So is there any other workaround? I need something that takes an input string with an expression and returns an output string with the derivative of that expression.

Thank you!

4

1 回答 1

2

这不是一个完整的答案,因为正如他们所说,TMTOWTDI。但是,为了能够使用 Symbolic++,您需要具有程序级别的访问权限……也就是说,您不能真正编写和编译

Symbolic x("x");
Symbolic x2 = x^2;

但你需要一些东西(但灵活)

if (there_is_x_symbol) {
    expr = Symbolic x("x");
}
if (raise_to_the_2nd_power) {
    expr = expr^2;
}

要以有机方式执行此操作,您需要一个解析器,以及一个解析器,它不仅可以导出evaluate()方法,而且可以让您访问表达式树,例如

     ( multiply )
      /        \
  ( 2 )       ( square )
                 \
                ( x )

您可以递归评估:

left = myEvaluate(node.left)
right = myEvaluate(node.right)
if (node.op == multiply) {
    return left * right;
}
if (node.op == square ) {
    return right ^ 2;
}
...

muparser(和 muparserX)库似乎不允许这样做。

还有其他几个代数解析器,例如看起来很有希望。您可以使用供应商解析器算法,并编写您自己的使用 Symbolic++ 并输出 Symbolic++ 表达式的 Evaluator。

你不需要深入的语法知识来破解这样的解析器——大多数只会生成一个反向波兰表示法堆栈,这就是你真正需要知道的。

在 bocca al lupo :-)

于 2014-10-17T19:32:20.397 回答