Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

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

Search the Archive

Re: SetDelayed and Evaluate

  • To: mathgroup at smc.vnet.net
  • Subject: [mg104509] Re: SetDelayed and Evaluate
  • From: David Bailey <dave at removedbailey.co.uk>
  • Date: Sun, 1 Nov 2009 17:59:17 -0500 (EST)
  • References: <hcjiul$jmr$1@smc.vnet.net>

Peter wrote:
> Hi group,
> 
> after years of experience with Mathematica I've got a simple (?)
> problem:
> 
> When answering to a question on the student support forum (http://
> forums.wolfram.com/student-support/topics/21448/) I tried fo myself
> the folowing variants:
> f[z_?NumericQ]:=Compile[{{x,_Real}},x-x^2][z];
> g[z_?NumericQ]:=Evaluate[Compile[{{x,_Real}},x-x^2]][z];
> and got the following results:
> In[6]:= Timing[Do[NMaximize[f[x],x],{1000}]]
> Out[6]= {35.871,Null}
> In[7]:= Timing[Do[NMaximize[g[x],x],{1000}]]
> Out[7]= {35.962,Null}
> 
> ~1 ms per NMaximize is OK, because there are background-processes
> running.
> 
> But I expect f to compile x-x^2 at every call to f and g to compile
> once on time of definition. Therefore I expected g to be significantly
> faster than f.
> 
> Where am I wrong?
> 
> TIA,
> Peter Pein
> 
If you evaluate ?g you can see that the Evaluate has not done what you 
expected. The reason is that Evaluate would need to apply to the whole 
second argument of SetDelayed. Calls to Evaluate nested inside 
expressions that are not themselves evaluated, do not work:

?g

Global`g

g[z_?NumericQ]:=Evaluate[Compile[{{x,_Real}},x-x^2]][z]

Therefore either use

g=Compile[{{x,_Real}},x-x^2]

or, if you want to keep the ?NumericQ qualification

With[{cc = Compile[{{x, _Real}}, x - x^2]}, g[z_?NumericQ] := cc[z]]

I would be inclined to use a more complicated function to ensure that 
the timing is not swamped by the function startup code, and/or the 
actual NMinimize code. Also, tor timing purposes, I always loop over a 
calculation to get a time of at least several seconds, otherwise the 
time is rather unreliable.

David Bailey
http://www.dbaileyconsultancy.co.uk






  • Prev by Date: Re: SetDelayed and Evaluate
  • Next by Date: Re: dynamicmodule with f[x_] possible?
  • Previous by thread: Re: SetDelayed and Evaluate
  • Next by thread: Re: SetDelayed and Evaluate