Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2007
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Block vs. ReplaceAll

  • To: mathgroup at smc.vnet.net
  • Subject: [mg79907] Block vs. ReplaceAll
  • From: Neil Stewart <neil.stewart at warwick.ac.uk>
  • Date: Wed, 8 Aug 2007 04:57:16 -0400 (EDT)
  • Reply-to: Neil Stewart <neil.stewart at warwick.ac.uk>

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: Re: How show Locator point and its image under a function?
  • Next by Date: Re: Beta function, Integral
  • Previous by thread: Re: FindRoot can NOT handle mixed real and complex variables
  • Next by thread: Re: Block vs. ReplaceAll