0
$\begingroup$

Some nonlinear equations can have many solutions for a given parameter and I would like to know how the number of solutions varies with respect to a parameter $a$.
I would like to solve:
$ax^2+x-1=e^x$
I defined a function in Mathematica:
sol[a_]=NSolve[Exp[x] == a*x^2+x-1, x, Reals]
It works fine.
For some parameters the equation has more than one solution (I am almost sure it can have at most three solutions) and I want to define three functions, one for each solution (if exists, otherwise it should return eg. 0).
I tried to define second such function as below:
sol2[a_]=If[Length[sol[a]] > 1, sol[a][[2]], 0]
It should return second solution (if exists).
However, sol[a] is not treated by Mathematica as a list of solutions for particular $a$, but as one symbol, so Length[sol[a]] is always equal to the same number (3), not related to actual number of solutions.
Moreover, the function sol2[a] always returns x, as a second element in definition of sol[a] function (the third function sol3[a] returns Reals).
How can I make Mathematica treat sol[a] as a list of solutions for particular parameter $a$?

$\endgroup$

2 Answers 2

0
$\begingroup$

and I want to define three functions, one for each solution

I think you are making things too complicated. Why not define one function and pass it the argument of the number of solution you want?

(if exists, otherwise it should return eg. 0).

I do not think this is good idea. What if the solution itself was zero? How will you know if it returned zero because you asked for solution number 4 but there was only 3 solutions, or if solution 4 happened to be zero? you can use Null as return value instead.

something like

ClearAll[sol, a, x]
sol[a_, n_Integer?Positive] := Module[{sol},
  sol = NSolve[Exp[x] == a*x^2 + x - 1, x, Reals];
  If[Length[sol] >= n, sol[[n]], Null]
  ]

And now you can do

Mathematica graphics

One function only. The second arguments asks for the nth solution. If there is no such solution, it returns nothing. If you do not want to return Rule but the actual value, use

ClearAll[sol,a,x]
sol[a_,n_Integer?Positive]:=Module[{sol},
   sol=Values@NSolve[Exp[x]==a*x^2+x-1,x,Reals];
   If[Length[sol]>=n,First@sol[[n]],Null]
]

Mathematica graphics

$\endgroup$
1
$\begingroup$

ContourPlot shows possible solutions

ContourPlot[Exp[x] == a*x^2 + x - 1, {x, -10, 10}, {a, -5, 10}]

enter image description here

solx[a_?NumericQ] := NSolve[{Exp[x] == a*x^2 + x - 1, -10 < x < 10}, x]

solx gives 0,1,2 or 3 solutions depending on a. No need to set arbitrary 0 in the result.

$\endgroup$

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.