1
$\begingroup$

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:

enter image description here

enter image description here

enter image description here

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]
]
$\endgroup$
0

1 Answer 1

2
$\begingroup$

It's slowing down because the function vard[x] gets more and more complicated as the iterations increase. By 10 iterations it is many pages long, with hundreds of sines and cosines. One way to speed it up is to simplify the calculations as you go. For example, replace your vard[x] with:

vard[x_] = FullSimplify[VariationalD[(i[x] - j[x])^2, j[x], x] 
            /. {i[x] -> a[x], j[x] -> f[x]}];

Now the 10th iteration is not much longer than the first...

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.