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

Warren Weckesser warren.weckesser at gmail.com
Sun Nov 3 14:56:41 CET 2019


On 11/3/19, Alexey Sheplyakov <asheplyakov at yandex.ru> wrote:
> Hi!
>
>>>      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*:


Thanks Alexey.

A simple string substitution such as 'I' -> 'i' would not be safe.
What if 'i' is also used in the expression?  What if names such as
'I1', 'I2', 'Ion', etc., are also used?  But maybe a regex-based
substitution could work.  (I'd rather not have to write a complete
expression parser just for this--I'd rather let GiNaC to the work. :)

Warren


>
>
> #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,
>        Alexey
> _______________________________________________
> GiNaC-list mailing list
> GiNaC-list at ginac.de
> https://www.cebix.net/mailman/listinfo/ginac-list
>


More information about the GiNaC-list mailing list