Question about updating functions

  • Context: Mathematica 
  • Thread starter Thread starter member 428835
  • Start date Start date
  • Tags Tags
    Functions
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 2K views
member 428835
Hi PF!

When using Mathematica I input the code
Code:
f1[a_, n_] := 
 f1[a, n] = 
  Join[Table[LegendreP[k, x], {k, 0, n, 1}], 
   Table[LegendreP[k, x], {k, 1, n, 1}]]
Then when I type ##f1[1, 3] ## I get an output. I then change the second table of ##f1## to start at 0 instead of 1, recompute that, and then recompute ##f1[1, 3] ## yet I get the same output. Is there something I need to understand here or is this a bug?
 
Physics news on Phys.org
This is not a bug, this is correct behavior. When you type f1[1,3] the first time then it calculates it and stores the value. Then it simply recalls the stored value next time you type f1[1,3], so it never re calculates it. The fact that you changed the calculation doesn't clear the stored value.
 
Dale said:
This is not a bug, this is correct behavior. When you type f1[1,3] the first time then it calculates it and stores the value. Then it simply recalls the stored value next time you type f1[1,3], so it never re calculates it. The fact that you changed the calculation doesn't clear the stored value.
Sorry if this is redundant, but I want to make sure I'm understanding you: I type the ##f1:=...##, execute the command, then execute ##f1[1,3]##. Then change ##f1:=...## and re-execute that command, then again execute ##f1[1,3]##, and the answer will always be the same as the first time?

Thanks for your speedy response.
 
joshmccraney said:
the answer will always be the same as the first time?
Yes.

The := operator and the = operator both set a mapping from the symbol on the left to the symbol on the right. The difference is that the = symbol immediately evaluates the right side and then maps the left side to the result of he evaluation. The := symbol does not evaluate the right side, but makes the mapping and waits for the left side to appear before evaluation.

So when I type f[x_] := f[x] = 2x it makes a mapping between f[x_] and f[x] = 2*4. The right side is not evaluated, but is kept just as code. Later, if I write f[4] then the computer recognizes that as a symbol matching f[x_] with x set to 4. So it pulls up the right side that is associated with f[x_] and only now evaluates it but with all occurrences of x replaced by 4. So it now evaluates f[4]=2*4. This time the right side is evaluated immediately returning 8, and a new mapping from f[4] to 8 is stored.

Now, if f[4] is called again then that matches both f[x_] and f[4] but the rule is that the most specific mapping takes precedence, so the symbol is matched to 8, which is returned immediately without recalculation.
 
  • Like
Likes   Reactions: member 428835