[GiNaC-list] Undefine the predefined numeric consant 'I'?

Alexey Sheplyakov asheplyakov at yandex.ru
Sun Nov 3 08:32:21 CET 2019


>>      Would a string substitution be a solution to this?
> Not really. The problem is not just the output. Ginac sets 'I' to be
> a predefined constant, so the code below prints
> e: -3-I*x
> de/dI: 0
> instead of the desired
> e: 3*I^2 - x*I
> de/dI: 6*I - x

Actually the string substitution is enough. The trick is to replace "I" with something else in the *input*:

#include <iostream>
#include <ginac/ginac.h>
using namespace GiNaC;

int main(int argc, char **argv) {
    symbol I("I"), x("x");
    symtab table{{"i", I}, {"x", x}};
    parser reader{table};
    ex e = reader("3*i*i - x*i");
    ex eprime = e.diff(I);
    std::cout << "e = " << e << ", de/d" << I << " = " << eprime << std::endl;
    ex check = eprime - (6*I - x);
    if (!check.expand().is_zero()) {
        return 1;
   return 0;

The output of the above program is:

e = -I*x+3*I^2, de/dI = 6*I-x

> For now, I'll just disallow the use of 'I' as a user-defined variable.

It's sort of similar to having a variable named `class` in a C++ code. I guess it's possible
to hack the parser that way, however it's simpler to pick a different name (`theclass`, `class_`, etc)

Hope this helps,

More information about the GiNaC-list mailing list