Derivative of a General Expression (Toolkit TKMath: Package ExprIntrp & Package Expr)

Hi All,

I'm using the TKMath Toolking to obain a symbolic expression of a function. Please see code snippet below. The expression evaluates but the derivative always returns 0. Is there something I'm doing wrong? Thanks in advance.

 

//Derivative of a General Expression (Toolkit TKMath: Package ExprIntrp & Package Expr)

#include <TDataStd_AsciiString.hxx>
#include <ExprIntrp_GenExp.hxx>
#include <Expr_NamedUnknown.hxx>

TCollection_AsciiString exprStr(Standard_CString("x^2 + x"));
opencascade::handle<ExprIntrp_GenExp> exprIntrp = ExprIntrp_GenExp::Create();
exprIntrp->Process(exprStr);

if (exprIntrp->IsDone())
    {
        opencascade::handle<Expr_GeneralExpression> exp = exprIntrp->Expression();

         const opencascade::handle<Expr_NamedUnknown> varX = new Expr_NamedUnknown("x");

         exp->Derivative(varX); // Derivative of "x^2 + x" with regards to "x" always returns "0"!
    }
    

Regards

Kulani

Lincoln Nxumalo's picture

No worries I managed to figure it out:-)

Mario Mancusi's picture

I'm not expert with this class and I did not test, but from doxy documentation and inheritance diagram of Expr_GeneralExpression class I understand that you should compose your symbolic string using classes like Expr_Sum, Expr_Prod, Exp_PolyFunction, instead of writing directly the expression in a string. I hope this may help you.

Regards.

Mario

Lincoln Nxumalo's picture

Hi Mario,
Thank you for taking the time to respond. I also came to the very same conclusion as you after struggling for a bit. However, it turns out it possible to differentiate the expression created from the string. The mistake I was making is creating a new "x" variable (varX = new Expr_NamedUnknown("x");). You are supposed to obtain the unknown variable "x" from the expression and differentiate with regards to that named unknown.