I have a function $f$, and I would like to modify it iteratively to approach another one called $a$ (not because I think this is the best way to do anything, but for experimentation). For this, I use VariationalD
:
Needs["VariationalMethods`"]
I define the original $f$ and the target function $a$:
f[x_]=1.2*Sin[10*x]
foriginal[x_]=f[x]
a[x_]=Sin[2*x]
Then I calculate the functional derivative of the functional
$$F=\int(a-f)^2\mathrm{d}x$$ with respect to $f$. I add a function proportional to this functional derivative to $f$, and the result will be the new $f$. I plot what happens after every iteration. Code:
For[i=0,i<50,i++,
vard[x_]=VariationalD[(i[x] - j[x])^2, j[x], x] /. {i[x] -> a[x], j[x] -> f[x]};
f[x_]=f[x]-vard[x]*0.05;
Plot[{foriginal[x],a[x],f[x]},{x,0,Pi},PlotLegends->"Expressions",PlotLabel->i]// Print;
Print[i]
]
The plots are as expected, some examples:
The green line approaches the yellow one, as expected.
However, each cycle in the iteration takes longer and longer seemingly. I am working in an online notebook, and it interrupts execution after ~15th cycle. The first few are lightning fast though.
I would like to understand why this slowdown happens.
Why are iterations getting longer in my for loop, and how can I fix that?
The whole code in one block:
Needs["VariationalMethods`"]
f[x_]=1.2*Sin[10*x]
foriginal[x_]=f[x]
a[x_]=Sin[2*x]
For[i=0,i<50,i++,
vard[x_]=VariationalD[(i[x] - j[x])^2, j[x], x] /. {i[x] -> a[x], j[x] -> f[x]};
f[x_]=f[x]-vard[x]*0.05;
Plot[{foriginal[x],a[x],f[x]},{x,0,Pi},PlotLegends->"Expressions",PlotLabel->i]// Print;
Print[i]
]