Lingering Definitions: when calculations go bad
One aspect of Mathematica that sometimes confuses new users, and has confused me often enough, is the Lingering Definition Problem. Here's a quick experiment you can do, to see the problem clearly.
1: Launch (or re-launch) Mathematica, create a new notebook, and evaluate the following expression:
x = 2 + 2
2: Now close the notebook document without saving (and without quitting Mathematica), and create another fresh notebook. Evaluate this:
The result can be surprising to beginners - after all, you think you've just removed all visible traces of
x, closing the only notebook with any record of it, and yet, it still exists, and still has the value 4.
To explain this, you need to know that when you launch the Mathematica application, you're launching two linked but separate components: the visible front-end, which handles the notebooks and user interaction, and the invisible kernel, which is the mathematical engine that underpins the Mathematica system. The notebook interface is like the flight deck or operating console, and the kernel is like the engine, hidden away but ready to provide the necessary power.
So, what happened when you typed the expression
x = 2 + 2, is that the front-end sent it to the kernel for evaluation, and received the result back from the kernel for display. The resulting symbol, and its value, is now part of the kernel. You can close documents and open new ones, but the kernel's knowledge of the symbol
x is unaffected, until something happens to change that.
And it's these lingering definitions that can confuse you - symbols that are not visible in your current notebook are still present and defined in the kernel, and might affect your current evaluations.
This also affects subscripted expressions - consider the following evaluation, where the initially innocent symbol
i is assigned an explicit value:
If you want to use subscripted symbols in a more robust fashion, you should use e.g. the Notation package.
There are a couple of things you can learn to do to avoid problems caused by Lingering Definitions. Before you provide definitions for specific symbols, clear any existing values that you've defined so far in the session, with the
Or you can clear all symbols in the global context, using
When all else fails, quit the kernel (choose Evaluation>Quit Kernel from the menu or type
Quit, thereby forgetting all the symbols (and everything else) that you've defined in the kernel.
Mathematica allows you to keep your notebooks separate, so that they don't share the same symbols. See this Q and A for more.