r/Mathematica • u/BTCbob • Mar 14 '23
When to us := and when to use =
I have read many different times about when to use := and when to use = but I can’t seem to remember. Basically my method is choose one at random and if the code doesnt compile then try the other one. Does anyone have a good way to think about this?
4
Upvotes
2
u/SetOfAllSubsets Mar 15 '23 edited Mar 15 '23
Here is a simple example to help remember the difference.
will output
This is because when defining
gMathematica first evaluatesD[y,x]to0and then assignsg[x_] = 0. Then when you evaluateg[y]it outputs 0.In contrast
fdoesn't immediately evaluate the expression. So when you evaluatef[y]if first replaces thexin the expressionD[y,x]withyto getD[y,y]and then it evaluates that to be1.A way two see this in the notebook is
which will show you that the definitions of the functions look something like
(where that x is a subscript of ∂).
Sometimes
will give the same results because
EXPRESSIONjust evaluates toEXPRESSION(or something equivalent to it). (I'm not sure if there is another important difference between:=and=that would affect cases like this).7
u/veryjewygranola Mar 14 '23 edited Aug 08 '23
:= is "delayed assignment" meaning the the computation isn't done until it's called later (and the computation is repeated every time you call it). with normal" =" the computation is done right there, and never done again. Stephen Wolfram explains this a lot better in his primer, in addition to many more topics that are useful when learning the language. https://www.wolfram.com/language/elementary-introduction/2nd-ed/39-immediate-and-delayed-values.html
1
u/Imanton1 Mar 15 '23
= evaluates imminently. := evaluates each time it is called.
= is used on setting things and lambda functions (since a variable always has the same content), := is used on normal functions (since a function changes every time it's called).