2
$\begingroup$

for example I am trying to execute this code:

f[x_, a_] := Sin[x] - a
g[a_] := NSolve[f[x, a] == 0 && x > 0 && x < 6]
Plot[x /. g[a], {a, -1, 1}]

Then I'm receiving plot with "holes" like this one:enter image description here

How can I avoid this effect? After all I insist to use NSolve function, so any "parametric" solutions don't satisfy me.

$\endgroup$
1
  • $\begingroup$ will PlotPoints solve your problem? also, in this occasion, I advise you yo use FindRoot instead. $\endgroup$
    – Wjx
    Jul 2, 2016 at 4:35

1 Answer 1

2
$\begingroup$

The problem is that the first argument in Plot must have a constant form. In your example sometimes 2 solutions are found and sometimes 1 solution only. Hence the form varies between {_,_} and {_}. With the following modification, the form {_,_} occurs Lebesgue almost surely, which suffices:

f[x_, a_] := Sin[x] - a
g[a_] := NSolve[f[x, a] == 0 && x > 0 && x < 2 \[Pi]]
Plot[x /. g[a], {a, -1, 1}]

enter image description here

However, as soon as f is defined differently, this may no longer be the case, so different code should be used.

Also, the plot dependents on the order of the solutions from NSolve in an unfortunate fashion:

f[x_, a_] := Sin[x] - a
g[a_] := RandomSample[NSolve[f[x, a] == 0 && x > 0 && x < 2 \[Pi]]]
Plot[x /. g[a], {a, -1, 1}]

enter image description here

For the function in the question you could do:

ParametricPlot[{Sin[x], x}, {x, 0, 6}, AspectRatio -> 1/GoldenRatio]

Which also works for other functions if they exhibit a left inverse. Is that the case for all functions in your context?

$\endgroup$
2
  • $\begingroup$ Thanks a lot! Your explanations were really helpful. $\endgroup$
    – Noct
    Jul 2, 2016 at 15:54
  • $\begingroup$ Recommend that you add the option Exclusions -> 0 to the Plot $\endgroup$
    – Bob Hanlon
    Jul 2, 2016 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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