[Date Index]
[Thread Index]
[Author Index]
Re: Block vs. ReplaceAll
*To*: mathgroup at smc.vnet.net
*Subject*: [mg79968] Re: Block vs. ReplaceAll
*From*: ben <benjamin.friedrich at gmail.com>
*Date*: Thu, 9 Aug 2007 06:27:45 -0400 (EDT)
*References*: <f9c1cs$6jg$1@smc.vnet.net>
Dear Neil,
I frequently encounter situations where I need
an extra symbol to pass the value of a variable
( classical example:
f = x;
g[x_] := f;
g[1]==x
f=x
g[xval_]:=f/.{x->xval}
g[1]==1)
Why not use something similiar here?
sol2={aval->a,bval->b}/.Last[solution]
Block[ {a=aval/.sol2,b=bval/.sol2} , ... ]
Bye
On 8 Aug., 11:11, Neil Stewart <neil.stew... at warwick.ac.uk> wrote:
> 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.
Prev by Date:
**data format on y axis**
Next by Date:
**Re: NMinimize a function of NMaximize**
Previous by thread:
**Block vs. ReplaceAll**
Next by thread:
**Re: Block vs. ReplaceAll**
| |