5

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.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
user49535
  • 1,225
  • 6
  • 9

2 Answers2

8

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

Filipe Miguel
  • 515
  • 2
  • 8
5

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 !

Ulrich Neumann
  • 53,729
  • 2
  • 23
  • 55