[GiNaC-list] Converting an expression to std::string and back again

Richard B. Kreckel kreckel at in.terlu.de
Tue Mar 28 22:49:47 CEST 2017

On 03/28/2017 09:57 AM, Robert Hai wrote:
> for a project I need to convert a std::string to an ex, diff it and then convert it back to a std::string. For the conversion from std::string to ex I found this constructor : 
>     /** Construct example from string and a list of symbols. The input grammar is * similar to the GiNaC 
>     output format. All symbols and indices to be used * in the expression must be specified in a lst in the 
>     second argument. * Undefined symbols and other parser errors will throw an exception. */ 
>     ex(const std::string &s, const ex &l);
> at http://www.ginac.de/reference/classGiNaC_1_1ex.html#ace68037326c1a2b8c93a56716599ec7a
> So I tried doing the following :
>     symbol x("x");
>     ex expression;
>     ex e("x^2",expression);
>     std::cout << diff(e,x) << std::endl;
> But this leads me to this exception :
> std::invalid_argument: find_or_insert_symbol: symbol "x" not found
> Note that I tried using expression and e in diff(e,x). Unfortunately I could not find any documentation on how to convert the expression diff returns to a std::string.

The second argument should be a GiNaC::lst with all symbols that occur
in the string. Try this:

        symbol x("x");
        lst syms = {x};
        ex e("x^2", syms);
        std::cout << diff(e, x) << std::endl;
        // -> 2*x

All my best,
Richard B. Kreckel

More information about the GiNaC-list mailing list