1
$\begingroup$

Even though there is a good example of how to plot roots with slider example by Bob Hanlon , I am still struggling in implementing a modified one for my purpose. I have a very complicated polynomial (quartic) whose coefficients are represented with a long formulas made of coefficients (a,b,c,d). For sake of simplicity, I have the following code:

f=a-b*x^2+c*d*x^4
f1[x,a,b,c,d]:=f
solution= NSolve[f==0,x]
g[x,a,b,c,d]:=solution

I am struggling to understand how to include a,b,c,d coefficients for solution as sliders so that solution is plotted as red dots as shown by Hanlon. Any suggestions?

$\endgroup$
3
$\begingroup$
Clear[f]

f[x_, a_, b_, c_, d_] := a - b*x^2 + c*d*x^4

Manipulate[
 roots = x /. NSolve[f[x, a, b, c, d] == 0, x];
 pts = Select[{#, 0} & /@ roots, Element[#[[1]], Reals] &]// Union;
 {xmin, xmax} = If[Length[pts] > 1,
   MinMax[pts[[All, 1]]], {-1, 1}];
 Column[{
   StringForm["roots = ``", roots],
   Plot[f[x, a, b, c, d], {x, xmin, xmax},
    Epilog -> If[Length[pts] > 0,
      {Red, AbsolutePointSize[6], Point[pts]}, {}],
    ImageSize -> 500]}],
 Grid[{{Control[{{a, 0}, -5.0, 5.0, 0.1, Appearance -> "Labeled"}],
    Control[{{b, 1}, -5.0, 5.0, 0.1, Appearance -> "Labeled"}]},
   {Control[{{c, 1}, -5.0, 5.0, 0.1, Appearance -> "Labeled"}],
    Control[{{d, 1}, -5.0, 5.0, 0.1, Appearance -> "Labeled"}]}}]]

enter image description here

EDIT: For versions prior to v10.1 when MinMax was added, change the above definition of {xmin, xmax}to

{xmin, xmax} = 
 If[Length[pts] > 1, {Min[pts[[All, 1]]], Max[pts[[All, 1]]]}, {-1, 
   1}]
|improve this answer|||||
$\endgroup$
  • $\begingroup$ Min,Max are not the same shape error message $\endgroup$ – Aschoolar Jun 15 '17 at 0:39
  • $\begingroup$ Is it possible to have NSolve for root outside Manipulate so that already calculated solution can be used inside Manipulate $\endgroup$ – Aschoolar Jun 15 '17 at 0:53
  • 1
    $\begingroup$ @Aschoolar - To make use of the Manipulate's parameters, the NSolve (or equivalent) must be inside the Manipulate. You could use Show inside the Manipulate to display an externally generated Plot along with the Plot inside. $\endgroup$ – Bob Hanlon Jun 15 '17 at 1:07
  • $\begingroup$ @ Bob, Two error messages 1) Set::shape: {xmin,xmax} and MinMax{-1,0,0,1} are not the same shape. 2) Plot::plln Limiting value in xmin {x, xmin, xmax} is not a machine-sized real number $\endgroup$ – Aschoolar Jun 16 '17 at 0:41
  • $\begingroup$ I copied and pasted twice and verified each line....the same results....error occurs maybe because of different version of mathematica. Mine is v9. I have seen cases of different version collision. $\endgroup$ – Aschoolar Jun 16 '17 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.