2

I am fairly new to Mathematica. I am working my way through a number of books. I have been looking at the use of SetDelayed and want to confirm that my understanding is correct. I define a function as follows.

f[x_]:= f[x] = x;

When I evaluate ?f, I can see a rule for this function. Now each time I evaluate f, I see another rule is created for f. So by declaring the function as above, I ensure that for any given value of x the function will only be evaluated once.

Suppose I had declared functions f and g as follows.

f[x_] := f[x] = Sin[x] + Cos[x];
g[x_] := Sin[x] + Cos[x];

Am I correct in saying that, for any given x, f will only be evaluated once? That is, for a given value of x, Sin[x] and Cos[x] will only be called once; whereas in the case of g, each time g is called, Mathematica will evaluate both Sin[x] and Cos[x]? Will using Trace confirm this?

DavidC
  • 16,724
  • 1
  • 42
  • 94
David McHarg
  • 1,643
  • 1
  • 15
  • 28
  • 1
    Yes, you're correct. It's more apparent with something like f[x_] := f[x] = (Print[x];x). – Szabolcs Mar 08 '13 at 13:37
  • Thanks. Is it possible to run out of space in the global rule/name space ? In effect each time i call f[x] mathematica is creating a new rule so if i call the function n times i end up with n rules. – David McHarg Mar 08 '13 at 13:42
  • It is possible to run out of memory with this technique, but with most current computers this not the problem it was, say, in the 1990s. Mathematica is very good at getting all the memory it needs. – m_goldberg Mar 08 '13 at 13:53
  • see http://mathematica.stackexchange.com/search?q=memoization and http://en.wikipedia.org/wiki/Memoization and http://reference.wolfram.com/mathematica/tutorial/FunctionsThatRememberValuesTheyHaveFound.html – DavidC Mar 08 '13 at 14:09
  • Search for memoization on this page There's an implementation that will auto-free memory if too many results are remembered, but it only works for numerical arguments. I believe there were better implementations somewhere on this site. Someone will hopefully find them and give you a link. – Szabolcs Mar 08 '13 at 14:19
  • I think that question (and all its answers) pretty much address this question, so I'll mark it as duplicate so that others will know where to look as well. If that doesn't answer your question, please let me know (and the part that isn't answered). – rm -rf Mar 08 '13 at 18:28

0 Answers0