Re: Hold[] ReleaseHold[] ? or what ?

*To*: mathgroup at smc.vnet.net*Subject*: [mg60189] Re: Hold[] ReleaseHold[] ? or what ?*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Wed, 7 Sep 2005 04:03:48 -0400 (EDT)*Organization*: The Open University, Milton Keynes, U.K.*References*: <dfiuvc$p7n$1@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

lupos wrote: > hi all, > > why does the following code work as hoped ? > > In[1] > fn[u_Real] := NIntegrate[Sin[x + u], {x, 1, 2}]; > FindMinimum[fn[u], {u, 0}] > > Out[2]= > {-0.9588510772084058, {u -> -3.070796346594197}} > > > > but the next line generates some warnings/errors altough calculating > correctly. > how can the situation be fixed in a nice way ? > maybe some Hold[] / ReleaseHold[] ? > > In[3]:= > FindMinimum[NIntegrate[Sin[x + u], {x, 1, 2}], {u, 0}] > > Out[3]:= > NIntegrate::inum : Integrand Sin[u+x] is not numerical at {x} = {1.5`}. > NIntegrate::inum : Integrand Sin[u+x] is not numerical at {x} = {1.5`}. > NIntegrate::inum : Integrand Sin[u+x] is not numerical at {x} = {1.5`}. > {-0.958851077208406, {u -> -3.0707963268148295}} > > > thanks for any hints > robert. > Hi Robert, *NIntegrate* _must_ know the value of ALL the values/parameters before hand. To do the integration within the function *FindMinimum* you must use *Integrate*, that is first you ask Mathematica to do a symbolic integration with some parameter still unevaluated (operation that symbolic integration knows how to handle) then to find a minimum with a starting value of zero for the variable/parameter u. So, you may ask why using *NIntegrate* within a function definition works. It has worked in your case just because you have used *SetDelayed* (symbol ":=") rather than *Set* (symbol "="); see the last couple of pair-In-Out lines in the following code extract: In[1]:= FindMinimum[Integrate[Sin[x + u], {x, 1, 2}], {u, 0}] Out[1]= {-0.958851,{u -> -3.0708}} In[2]:= Integrate[Sin[x + u], {x, 1, 2}] Out[2]= 2*Sin[1/2]*Sin[3/2 + u] In[3]:= % /. u -> 0 // N Out[3]= 0.956449 In[4]:= NIntegrate[Sin[x + u], {x, 1, 2}] NIntegrate::inum: Integrand Sin[u + x] is not numerical at {x} = {1.5`}. More... Out[4]= NIntegrate[Sin[x+u],{x,1,2}] In[5]:= NIntegrate[Sin[x + u] /. u -> 0, {x, 1, 2}] Out[5]= 0.956449 In[6]:= fn[u_Real] := NIntegrate[Sin[x + u], {x, 1, 2}]; In[7]:= fn[u_Real]=NIntegrate[Sin[x+u],{x,1,2}] NIntegrate::inum: Integrand Sin[u + x] is not numerical at {x} = {1.5`}. More... NIntegrate::inum: Integrand Sin[u + x] is not numerical at {x} = {1.5`}. More... Out[7]= NIntegrate[Sin[x + u], {x, 1, 2}] However, if we substitute a value for u, the command works In[8]:= fn[u_Real] = NIntegrate[Sin[x + u] /. u -> 0, {x, 1, 2}] Out[8]= 0.956449 Best regards, /J.M.