5
$\begingroup$

I am trying to evaluate a function, which has simplified form as below.

f[a_] := 5*a

X[a_, b_]:=Module[{A= f[a], g[b] = 6*b, x = A + g[b]}, x];

Table[ParallelTable[X[a, b], {b, 1, 6400}], {a, 1, 40}]

Now, my problem is that for 6400 runs over "b", f[a] is calculated every time, in spite of being put under the module. This is what, I want to avoid as for all the runs over 'b', f[a] to remain same. I am not able to figure out how to achieve this. Will appreciate any help.

$\endgroup$
2
  • 1
    $\begingroup$ try ClearAll[X];X[a_, b_]:=Module[{A= f[a], g[b] = 6*b}, A + g[b]];? $\endgroup$ – kglr Feb 5 at 12:52
  • $\begingroup$ ParallelTable[5 a + 6 b, {b, 1, 6400}, {a, 1, 40}] ? Seems there are only simple calculation? $\endgroup$ – wuyudi Feb 5 at 12:53
8
$\begingroup$

I am not sure if this is what you are looking for, but this may help. You can use memoization to define f such that every time it is evaluated, it stores the value in memory:

f[a_]:=f[a]=5*a

Now if you call f[3] twice, the first time he will compute 5*3 = 15, and the second time he will retrieve the value he has in memory and return 15.

I would also ditch the Module, as Mathematica is not very good at deleting old variables and this may end up eating all your ram.

Try:

X[a_,b_]:=With[{A=f[a], g[b]=6*b},A + g[b]]

(I suppose you don't need this if you follow my initial advice but in general, it is good practice to use With instead of Module).

$\endgroup$
4
  • 2
    $\begingroup$ f[a_]:=f[a] thing worked. I could not figure it out in three days !! Thanks by the way. $\endgroup$ – user49535 Feb 5 at 16:57
  • $\begingroup$ You are welcome :) $\endgroup$ – Filipe Miguel Feb 5 at 17:38
  • 1
    $\begingroup$ This is called memoization, just to clarify what the method is that is being used. $\endgroup$ – CA Trevillian Feb 6 at 19:14
  • $\begingroup$ I should actually add that in, I had forgotten the name of it $\endgroup$ – Filipe Miguel Feb 6 at 19:55
5
$\begingroup$

Change the definition X[a_,b_] to

X[a_, b_] := Module[{A = f[a], g = Function[b, 6 b]}, A + g[b]];
X[a,b] (*5 a + 6 b*)

That's it !

$\endgroup$

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