I have some code that I am porting from VBA to Mathematica. The original code processes data on an Excel spreadsheet. In Mathematica, I find it convenient to replicate the Excel spreadsheet data using global variables. I created a function that inadvertently depends on how the function is called. The original code is rather complicated. Here is simple code that has the same type of behavior.
testFn:=(
iter=1;
While[iter<=iMax,
u=f+1;
f=u^2;
Print["iter=",iter,"; u=",u,"; f=",f];
iter++;
];
{u,f}
);
The code is evaluated by 4 input statements:
f=0;u=0;iMax=3;
testFn
u
f
If all four input statements are evaluated at one time (select all 4 and shift-enter), the results for the last two statements are u=5 and f=25; however, if the statements are evaluated one at a time, the results for the last two statements are u = 458330 and f = 210066388900. (This is the correct result when you evaluate testFn twice in succession.)
I have found two ways to get the correct results every time - whether the data is evaluated one line at a time, or all lines together. These are shown below
Put testFn on the first line:
f=0;u=0;iMax=3;testFn
u
f
Suppress the output of testFn with a semicolon:
f=0;u=0;iMax=3;
testFn;
u
f
An even simpler function shows the same behavior:
testFn2:=(
u=f+1;
f=u^2;
{u,f}
)
As before, the following statements give different results depending on whether they are evaluated one line at a time, or as a group:
u=0;f=0;
testFn2
u
f
As before, putting the functional call "testFn2" on the first line, or suppressing the output of testFn2 with a semicolon solves the problem.
How do I modify the function so that the results do not depend on how the functions are evaluated (one at a time or in a group of statements)?
What's going on?
Thank you for your help!
MAK (Mathematica 10.0.2.0 on Windows 7)