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

MathGroup Archive 2010

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

Search the Archive

Re: FindRoot + Compile = incompatible (?)

  • To: mathgroup at smc.vnet.net
  • Subject: [mg111315] Re: FindRoot + Compile = incompatible (?)
  • From: Szabolcs Horvát <szhorvat at gmail.com>
  • Date: Tue, 27 Jul 2010 04:17:58 -0400 (EDT)
  • References: <i2joiv$fsk$1@smc.vnet.net>

On 2010.07.26. 12:38, Scot T. Martin wrote:
> Has anyone ever run into the problem of trying to use Compile'd functions
> within FindRoot?
>
> The error message is:
>
> "CompiledFunction::cfsa: Argument y at position 1 should be a machine-size
> real number."
>
> [Yes, the function still evaluates but in doing so the purpose of compile
> &  speed gets defeated.]
>
> The explanation for this error messages is found in ref/FindRoot:
>
> "FindRoot first localizes the values of all variables, then evaluates f
> with the variables being symbolic [1], and then repeatedly evaluates the
> result numerically." [1] That's why Compile[] fails.
>
> Here is a specific example of code that shows the problem:
>
> *****
>
> func = Compile[{x}, x^2];
>
> FindRoot[func[y] == 1, {y, 0.5, 1.5}]
>
> *****
>
> Anyone have thoughts on how to work around this aspect so that Compile'd
> functions can work within FindRoot and thus accelerate evaluation thereof?
> [Or is there an inherent reason why they shouldn't?]
>
> [My actual function is not "func"; my actual func is 3x faster as a
> Compile'd, hence my motivation to get FindRoot to work.]
>


Hello,

As you noticed, the problem appears because func[y] is evaluated by 
FindRoot even before a number is substituted for y.

A workaround is to define a function that is evaluated for numeric 
arguments only:

func2[x_?NumericQ] := func[x]

FindRoot[func2[y] == 1, {y, 0.5, 1.5}]



  • Prev by Date: Re: FindRoot + Compile = incompatible (?)
  • Next by Date: Re: A Question About Directive
  • Previous by thread: Re: FindRoot + Compile = incompatible (?)
  • Next by thread: Problem with Min Max between two functions