Re: Block vs. ReplaceAll

*To*: mathgroup at smc.vnet.net*Subject*: [mg80713] Re: Block vs. ReplaceAll*From*: Neil Stewart <neil.stewart at warwick.ac.uk>*Date*: Thu, 30 Aug 2007 02:27:12 -0400 (EDT)*Reply-to*: Neil Stewart <neil.stewart at warwick.ac.uk>

Thank you to everyone who has posted replies. Off-list, Daniel Lichtblau from Wolfram was kind enough to help me out. His solution is below. It uses the list of parameter values from NMinimize in a Block rather than with ReplaceAll as would be more usual. Block evaluates more quickly than ReplaceAll, and so is useful for bigger functions: > f[a_,b_] := a^2 + b^2 > g[a_,b_] := Count[Table[f[a,b], {10}], 0.] > solution = NMinimize[{f[a,b], a > 0 && b > 0}, {a, b}] > myBlock[f_,vars_,ruls_List] := Block[vars,ruls/.Rule:>Set;Apply[f,vars]/.ruls] > In[10]:= myBlock[g,{a,b},Last[solution]] > Out[10]= 10 Original post below: > Take a function f of some global variables and a function g that depends > on f. > > f := a^2 + b^2 (* f is a function of a and b, a and b are global > variables *) > > g := Count[Table[f, {10}], 0] (* g in turn depends on f *) > > Solutions can be found for a and b that minimize f. > > solution = NMinimize[{f, a > 0 && b > 0}, {a, b}] > {0., {a -> 0., b -> 0.}} > > But how is it best to use the solution? > > Block[{a = 0, b = 0}, f] (* Fast *) > 0 > > or > > f /. Last[solution] (* Slow *) > 0 > > For this trivial example obviously both are fast, but when f is non-trivial, > Block[] is much faster. > > Further for g, only Block[] works as I intend (counting the number of times > ten calls to f evaluate 0): > > Block[{a = 0, b = 0}, g] (* Fast and works as I intend *) > 10 > > g /. Last[solution] (* Slow, and doesn't count the number of times f is > zero as I intended *) > > I understand why this happens: Count[] counts the fs in the table in > symbolic form, before a and b are replaced and f is evaluated at 0. > > My question is, how is it best to take "solution" - which is a list of > replace rules - and use it in a Block[] statement - which requires a list > of assignments? I need the speed that Block[] gives by making replacements > before f is evaluated. I'm keen to keep the simplicity of having model > parametes as global variables to avoid having to pass model parameters > explicitly to model functions as this is messy with a non-trivial model.