# How to avoid repeated calculation of a function [duplicate]

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.

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

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).

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

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 !