Suppose that I have a function
f[x_,y_,z_]=x*y*z
and now suppose I want to consider a specific application where z
is a function of x
and y
,
For example, suppose I want to consider z=x^2*y^2
Obviously, in this simple example I could just plug in z
and define a new function g[x,y]=x^3*y^3
.
But in a more complicated example this is not feasible (for example, what if we instead had f[x_,y_,z_]:= x*y^2*z^3 + x^2*y*z^2 + x^(.2)y^(.8) z^(.1)
). I figure a more general approach is to define z[x,y]
separately and then evaluate f[x,y,z[x,y]]
. I am wondering about using a module to do this
Specifically, consider the following way to define z[x,y]
and calculate f[x,y,z[x,y]]
: (note: this MWE has typo, see bottom of Question for a fixed version)
g[x_,y_]:=Module[{zfunc},
zfunc[x_,y_]:=x^2*y*2;
f[x,y,zfunc[x,y]]
]
My question is, in the above code, is there a reason to use
:=
when definezfunc[x_,y_]
as opposed to using=
?
I ask because, if I wasn't using a module, say if i instead had
zfunc[x_,y_]:=x^2*y*2;
g[x_,y_]:=f[x,y,zfunc[x,y]]
then I would want to use :=
, because if I redefine zfunc
then I want g
to be evaluated with this new zfunc
. However, in the module zfunc
is local, so I think every time I call g
the module redefines zfunc
, even if i use =
instead of :=
?
Aside: I realize that a different solution could be to use a named pattern for the z
argument, i.e.
f[x_,y_, func_Symbol]:=x*y*func[x,y]
I am not asking about this solution though, I am asking whether, when using module to define z[x_,y]
as above, using :=
is different than using =
Edit: MWE had a typo (and I am leaving it unchanged above because some comments might be useful to others, and may not make sense if I remove the typo)
The MWE should be
f[x_,y_,z_]=x*y*z;
g[x_,y_]:=Module[{zfunc},
zfunc=x^2*y*2;
f[x,y,zfunc]
]
I will also try to rephrase my question, since I have not received an answer:
Question: is there a reason to use
zfunc:=x^2*y*2
instead ofzfunc=x^2*y*2
in the above MWE?
The usual reasons I think of to use =
instead of :=
are
- Computation time
Possibility that, in something like
f[x]=x^2
,x
may have been defined earlier already (but this can be avoided by using clear or a module or something)When using a module like in the MWE, the variable
zfunc
is local.- It is my understanding that this means, that every time the module is called Mathematica will define a new variable -- i.e.
zfunc$1
,zfunc$2
etc -- I imagine that this would erase the computation time benefit of using=
versus:=
.
f[x,y,zfunc]
. I can't see if that fixes it right now, but when I get a chance I'll do so and respond here. @xzczd, I was not aware of chat, and now is frozen. Sorry. $\endgroup$h[x_,y_]:= x^3 *2*y^2
$\endgroup$