1
$\begingroup$

I have a convergent function $f(x)$.

What I want to do is to create a table of values $f(x)$ until the difference in the two subsequent value satisfies some convergence criterion. Say, I want to stop if $f(x+1)-f(x)<0.1$. The function itself is very ugly and there are random components, so we cannot directly check when it passes the stopping criterion. How can I create a table of {f[1],f[2],\cdots,f[z]}, where z is the first number that passes the criterion.

$\endgroup$
1
$\begingroup$

As an example, let

f[x_] := LogisticSigmoid[x]

init = 0.; step = 0.5; tol = 0.02;

This method which relies on NestWhile[] is compact, but evaluates f repeatedly (which is fine if evaluating f is cheap):

Reap[NestWhile[# + step &, init, (f[#2] - Sow[f[#1]] > tol) &, 2]][[-1, 1]]

(Of course, this can also be written using FixedPoint[]; I'll leave writing out that version as an exercise for the reader.)

Otherwise, we can use Sow[]+Reap[] in While[] if evaluating f can be expensive:

res = f[init];
Join[{res}, Reap[While[True, new = f[init += step];
                       If[new - res > tol,
                          Sow[res = new], Break[]]]][[-1, 1]]]
$\endgroup$
  • $\begingroup$ Thanks, @J.M. I'll try out the second approach. One more quick question. If I want to Break after running 10 more iterations from the point the criterion is satisfied, how may I change the code to do that? $\endgroup$ – Andeanlll May 16 at 7:00
  • 1
    $\begingroup$ You should have put that extra requirement in your question... $\endgroup$ – J. M.'s discontentment May 16 at 7:02
  • $\begingroup$ @Andeanlll It would be better to ask another question entirely on this additional matter. $\endgroup$ – CA Trevillian May 17 at 2:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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