Expressions can be tricky

Clear[f, x] ;

If we set f to be an expression in terms of x, then set x to a particular value we get the expected result for f.  If we then change the value of x, we still get the expected result for f.

f = x^2 ; x = 3 ; f x = 4 ; f

9

16

However, if we re-run the same commands we get unexpected results.  This is because in the definition for f, the right hand side is evaluted first.  At this point x has a value of 4, therefore f is assigned 16.  As a result, we can change the value of x now, but f remains 16.

f = x^2 ; x = 3 ; f x = 4 ; f

16

16

Thus, we must clear the definition of x before re-running these commands to get the expected results.

Clear[x] ; f = x^2 ; x = 3 ; f x = 4 ; f

9

16

A better way around this problem is to use :=, which delays evaluation of the right hand side until the variable is used.

f := x^2 ; x = 3 ; f x = 4 ; f

9

16


Created by Mathematica  (September 8, 2003)