Re: Problems with Set, SetDelayed and replacement rules...
- To: mathgroup at smc.vnet.net
- Subject: [mg72287] Re: [mg72274] Problems with Set, SetDelayed and replacement rules...
- From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
- Date: Mon, 18 Dec 2006 06:56:08 -0500 (EST)
- References: <200612171120.GAA07339@smc.vnet.net>
On 17 Dec 2006, at 20:20, Johannes wrote: > Hi, > > I am working a lot with physics equations where I have on the one > hand variables, and on the other hand paramters, which depend on > other parameters which are only given by a polynome. > In the following (very simplified example) f is a function which > depends on variable x and parameters g and h which depend both on > parameter p: > > f[x_]:= g/h*x; > g[p_]= 1+p; > h[p_]=1+p^2; > params={g->g[p],h->h[p]}; > > For numerical application, I would like to define a second function > f with p as second variable. This I have done with different > methods, and there I noticed a difference that I can't explain > > f1[x_, p_] = f[x] /. params; > f2[x_, p_] := f[x] /. {g->g[p],h->h[p]}; > f3[x_, p_] := f[x] /. params; > > If I am now calculating f1[1,1], f2[1,1] and f3[1,1], f1 and f2 > deliver as expected a numerical value, but for f3[1,1] p isn't > replaced by its value 1. > > Can anybody explain me the differences, especially the differences > between f2 and f3? I suspected it to be exactly identical. > > And does anybody know a better method to treat parameters? My > problem is that when doing analytical transformations (Derivatives, > Integrations...), an immediate replacement of the parameters g and > h would make the result very hard to read, so I was searching for > an easy method to replace them as late as possible. > > Thanks in advance for any help, > Johannes > When you have a definition like this: f[a1_,a2_,...]:=Body and evaluate f[b1,b2,...] what happens is this. First b1,b2,... are literally substituted for a1,a2,... in Body and then Body is evaluated. So look at you secodn defintion: > f3[x_, p_] := f[x] /. params; > When you evaluate f3[1,1] there is no p on the right hand side to substitute 1 for, so it is not substituted. Only after the substitution params is evaluated, and then p appears but by now it is too late. I am not sure what sort of "readability" problem you are referring to? You could of course use: f3[x_, p_] := Evaluate[f[x] /. params] but I am not sure whether this helps? Andrzej Kozlowski
- References:
- Problems with Set, SetDelayed and replacement rules...
- From: Johannes <ml.johannes@gmail.com>
- Problems with Set, SetDelayed and replacement rules...