clad icon indicating copy to clipboard operation
clad copied to clipboard

Incorrect gradient for if-conditions with side-effects

Open gojakuch opened this issue 9 months ago • 0 comments

Clad does not handle if-condition side-effects for all cases. The below example gives incorrect derivative:

#include "clad/Differentiator/Differentiator.h"
#include <iostream>

#define show(x) std::cout << #x <<": " << x << "\n";

double fn(double u, double v) {
    double res = 0;
    double foo = v;
    res = foo;
    res += foo;
    if ((foo = u) > 10) {
        res += foo * v;
    }
    return res + foo;
}

int main() {
    auto fn_grad = clad::gradient(fn);
    double u, v;
    u = 3, v = 5;
    double du, dv;
    du = dv = 0;
    fn_grad.execute(u, v, &du, &dv);
    show(du);
    show(dv);
}

Output: du: 0 dv: 3

Expected Output: du: 1 dv: 2

Originally posted by @parth-07 in https://github.com/vgvassilev/clad/pull/891#pullrequestreview-2062368592

gojakuch avatar May 17 '24 10:05 gojakuch