Group Abstract Group Abstract

Message Boards Message Boards

Delay evaluation of implicit function defined using FindRoot?

Posted 9 years ago

Consider the following implicit function defined using FindRoot and I am looking for its maximum.

 f[a_] := Sqrt[a] x /. FindRoot[x^4 + a x - 1 == 0, {x, 5}]
 Plot[f[a], {a, 0, 10}]
 FindMaximum[f[a], {a, 0}]

Mathematica does find the solution after some error messages:

FindRoot::nlnum: The function value {624. +5. a} is not a list of numbers with dimensions {1} at {x} = {5.}.

ReplaceAll::reps: {FindRoot[x^4+a x-1==0,{x,5}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing

I want to get rid of these error messages, because if I make the implicit function more complicated, Mathematica will attempt to evaluate the function without the parameter value, resulting in very long calculations. Your help is very much appreciate.

POSTED BY: Owen Wu
4 Replies

Thank you all. This is truly helpful.

POSTED BY: Owen Wu

If all you want is getting rid of the error messages, write

FindMaximum[f[a], {a, 0}] // Quiet

POSTED BY: Tomas Garza

Another way is to use the Condition(/;) to check the Head of an input. The code below says "Do not fire f unless the input is a real number " aka a $MachinePrecision number.

In[34]:= f[a_]:=(Sqrt[a] x/.FindRoot[x^4+a x-1==0,{x,5}])/;SameQ[Head[a],Real]
In[36]:= FindMaximum[f[a],{a,0}]
Out[36]= {0.731432,{a->1.19628}}
POSTED BY: Shenghui Yang
Posted 9 years ago

The error message occurs when FindMaximum tries to evaluate f with a symbolic argument. Define f as restricted to a numerical argument.to avoid this:

f[a_?NumberQ] := Sqrt[a] x /. FindRoot[x^4 + a x - 1 == 0, {x, 5}]
POSTED BY: David Keith
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard