Local variables when defining function in Mathematica

4.4k Views Asked by At

I defined a function in Mathematica. It is a function of n, so f[n_]:=, but in the definition, I used a sum, $\sum_{k=0}^n$. So, the $k$ is just an index variable for the sum and no $k$ shows up in the final answer. As I was using this function I tried evaluating f[k-1] and got a weird answer, 0. I finally figured out that Mathematica was trying to do the sum $\sum_{k=0}^{k-1}$, or so I guess. So, my question is, is there a way to make the $k$ local so that this error never occurs? My fix for now was to change $k$ to $index$ and I will probably not use f[index] at any point.

3

There are 3 best solutions below

1
On BEST ANSWER

The function you are looking for is called Module. You can define it as

f[n_] := Module[{k}, Sum[a[k], {k,0,n}]]

so that the evaluation f[k-1] is possible.

4
On

Block might be better than Module -- when you use recursion, a local variable defined in Module will be shared across stack frames, Block will have a separate version of the variable in each call

0
On

An alternative to Module or Block is to use Formal Symbols. This allows for the cleanest code.

One may still run into trouble depending on how you choose to use Formal symbols elsewhere, but if you never use \[FormalK] in the argument to f you are safe.