2

I have a function which includes finding roots of an equation. the coeffs of the equation are the inputs of the function and have to be numerical before calling. NMaximize passes symbolic input into the fucntion first and causes problems and errors.

functio[a1_, b1_] := 
  Max[
    Abs[
      x /. 
        {ToRules[NRoots[x^3 - a*x^2 + b*x - 1 == 0 //. {a :> a1, b :> b1}, x]]}]];

sol1 = 
  NMaximize[{functio[a, b], a >= 0, a <= 1, b >= 0, b <= 1}, {a, b}][[1 ;; 2]]

Error message

-1+b\ x-a\ x^2+x^3==0 is expected to be a polynomial equation in the variable x with numeric coefficients."

Does anyone know how to avoid that error.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Gil Bert
  • 21
  • 1

1 Answers1

3

Your function definition should require arguments that satisfy NumericQ. Further it should be written more simply.

func[a_?NumericQ, b_?NumericQ] := 
  Max @ Abs[(List @@ NRoots[x^3 - a*x^2 + b*x - 1 == 0, x])[[All, 2]]]

Then

NMaximize[{func[a, b], a >= 0, a <= 1, b >= 0, b <= 1}, {a, b}]

gives

{1.46557, {a -> 1., b -> 0.}}

That this result is correct may be visually confirmed by

Plot3D[func[a, b], {a, 0, 1}, {b, 0, 1}, AxesLabel -> Automatic]

plot

Note

I also recommend using \[FormalX] in place of x in the arguments given to NSlove.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257