1
$\begingroup$

I programmed a recursive function and I want to see the evolution depending on the number of trials. I want to find the value of k for which the difference between $rec_i^k$ and $rec_i^{k+1}$ is equal or smaller than $10^{-6}$

The problem is that I get a recursionlimit error, this is for a homework so I spoke to the teacher and told me to reprogramm the whole thing using a different way and I absolutely don't have the time for that this is why I am looking for your help here.

Here's the code it stops when k reaches 1017 and I get the Recursionlimit error. If anyone knows how I can avoid that without changing my definition of functions it would be great !

Clear[f, x, rec, err, diff];

x[i_Integer] := x[i] = (i - 1)/100;   
f[x_] := (x - 1/3)^3 Sin[1.1*Pi x];
shape[x_] := Max[{0, f[x]}];         

rec[i_Integer, 1] := rec[i, 1] = shape[x[i]]; 
rec[101, _] = 0; 
rec[0, _] = 0; 
rec[i_Integer, k_Integer] := 
  rec[i, k] = Max[0.5*(rec[i - 1, k] + rec[i + 1, k - 1]), shape[x[i]]]; 

 k = 2; 
 While[ 
   diff = Table[Abs[rec[i, k] - rec[i, k - 1]], {i, 2,101}]; 
   err = Max[diff];
   err > 10^(-6), k++]

k 
$\endgroup$
4
  • $\begingroup$ Block[{$RecursionLimit = 10000}, < run your code >]. $\endgroup$
    – march
    Dec 2, 2015 at 23:48
  • 4
    $\begingroup$ I'm voting to close this question as off-topic because it is too localized; i.e, it applies only to the local situation and needs of its poster and answers will not benefit others. $\endgroup$
    – m_goldberg
    Dec 3, 2015 at 0:47
  • $\begingroup$ I would agree with m_goldberg, but not everybody knows how to deal with $RecursionLimit. It might be fair to ask the user to generalize the question. $\endgroup$
    – mgm
    Dec 3, 2015 at 0:55
  • $\begingroup$ Clearly on topic $\endgroup$
    – BigMistake
    Dec 12, 2023 at 4:26

1 Answer 1

0
$\begingroup$

If I rewrite your code a little, I don't get any recursion limit warnings. Rather I get k = 2020. I don't know if that is answer you are looking for, but it what your code produces.

f[x_] := (x - 1/3)^3 Sin[1.1*Pi x]
shape[x_] := Max[0, f[x]]

rec[101, _] = 0;
rec[0, _] = 0;
rec[i_Integer, 1] := rec[i, 1] = shape[(i - 1)/100]
rec[i_Integer, k_Integer] :=
  rec[i, k] = Max[0.5*(rec[i - 1, k] + rec[i + 1, k - 1]), shape[(i - 1)/100]]

k = 2;
While[
  Max @@ Table[Abs[rec[i, k] - rec[i, k - 1]], {i, 2, 101}] > 10^(-6),
  k++]

k

2020

$\endgroup$

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