1
$\begingroup$

I am tryin to calculate how many calls to a function my code is using.

Eval[k_] := Module[{i = 0},
  f[x_?NumericQ] := 
   f[x] = (i += 1; Piecewise[{{Sin[x]/x, 0 < x < 1}, {1, x == 0}}]);
  AdpSimpson[f, 0, 1, 10^(-k/4)];
  Print[i];
  ]

Where AdpSimpson is a code that calls on $f$ quite a bit. I am trying to Tabulate the amount of calls to $f$ my code is doing depending on $k$. This code is just returning $Null$. Not sure what the issue is. I am using module here since I want $i$ to be a local variable so it "resets" for each $k$.

What is going on?

I put the scoping tag since the code works outside of module. But I dont want to clear[i] after each count.

Full Code:

AdpSimpson[f_, a_, b_, err_] := Module[{h = (b - a)/2, S, hS, h2},
   S = h (f[a] + 4 f[a + h] + f[b])/3;
   h2 = h/2;
   hS = h2 (f[a] + 4 f[a + h2] + f[a + h])/3 + 
     h2 (f[a + h] + 4 f[a + h2 + h] + f[b])/3;
   If[Abs[S - hS]/15 < err, hS, 
    AdpSimpson[f, a, a + h, err] + AdpSimpson[f, a + h, b, err]]];

f[x_] := f[x] = Piecewise[{{Sin[x]/x, 0 < x < 1}, {1, x == 0}}];
L := Table[
  N[Abs[AdpSimpson[f, 0, 1, 10^(-k/4)] - 
     NIntegrate[
      Piecewise[{{Sin[x]/x, 0 < x < 1}, {1, x == 0}}], {x, 0, 
       1}]]], {k, 1, 30}]
T := Flatten[Table[FirstPosition[L, x_ /; x < 10^(-k)], {k, 1, 6}], 1]


Eval[k_] := Module[{i = 0},
  f[x_?NumericQ] := 
   f[x] = (i += 1; Piecewise[{{Sin[x]/x, 0 < x < 1}, {1, x == 0}}]);
  AdpSimpson[f, 0, 1, 10^(-k/4)];
  i
  ]


Table[Eval[k], {k, T}]
$\endgroup$
6
  • $\begingroup$ Do you want it to return i or Print i? Module[,,,, i] (no semi-colon after the i) would return i. The semicolon after the Print makes the Module return Null. Print returns Null anyway, so removing the last semicolon wouldn't make a difference. $\endgroup$ – Michael E2 Nov 14 '20 at 22:31
  • $\begingroup$ @MichaelE2 I want it to return updated $i$. $i$ represents the amount of calls for $f$. So I want Eval[k] to return i. I honestly do not know what the difference between print and return is so i will have to look into that $\endgroup$ – 2132123 Nov 14 '20 at 22:38
  • $\begingroup$ @MichaelE2 I have attached the full code, just in case. It is still not working in the format you suggested. $\endgroup$ – 2132123 Nov 14 '20 at 22:42
  • $\begingroup$ The problem is that you have two definitions of f. One of them does not update i. If I Block the other definition in Eval, I get a result: i.stack.imgur.com/1gcsH.png $\endgroup$ – Michael E2 Nov 14 '20 at 22:47
  • $\begingroup$ Also you memoize the evaluation of f, so that on subsequent calls, there will be no updating of i. (For instance, if you run the code multiple times.) $\endgroup$ – Michael E2 Nov 14 '20 at 22:50

Your Answer

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

Browse other questions tagged or ask your own question.