vgvassilev / clad

clad -- automatic differentiation for C/C++
GNU Lesser General Public License v3.0
290 stars 122 forks source link

Simplify generated code by eliminating zero terms to make it more readable #1026

Open gediminasel opened 3 months ago

gediminasel commented 3 months ago
#include "clad/Differentiator/Differentiator.h"

double twox(double x)
{
    return 2 * x;
}
int main()
{
    auto l_h = clad::differentiate(twox, "x");
    l_h.dump();
}

Gives the output:

The code is:
double twox_darg0(double x) {
    double _d_x = 1;
    return 0 * x + 2 * _d_x;
}

Although zero terms make it easy to see how the chain rule was applied and might be useful for debugging, they also make the output longer and more difficult to read. It would be nice to have an option for dump or a compile-time flag to do some simplifications on the generated code -- namely, eliminate multiplication by 0. I know that it's probably optimized out at later compilation stages but maybe something simple could be done in clad too.

vgvassilev commented 3 months ago

Yes, we have such a facility but it is not turned on by default.

We can implement a new flag something like -print-pretty and turn on the constant folder by default.

Similar to #50.