3
$\begingroup$

I was wondering if there was a way to use the Mathematica NSolve command to solve an equation that has a parameter with various values. An example of which is:

parameter = {1,2,3,4,5};

equation = x + parameter;

NSolve[equation == 0, {x}]

The output should be:

{-1,-2,-3,-4,-5}

Obviously, my NSolve expression does not give the above output, but if it did, it would make my world MUCH easier. As my actual equations are much more complex and my parameter lists can sometimes contain a lot of values, copy and paste has been tedious, to say the least!

Any help would be greatly appreciated.

$\endgroup$
1
  • 1
    $\begingroup$ Mathematica does the right thing, and NSolve should return a empty list, because the equations {1 + x == 0, 2 + x == 0, 3 + x == 0, 4 + x == 0, 5 + x == 0} are incompatible with each other. What you really mean is solving them one by one , not simultaneously. In this case, NSolve[# == 0, {x}] & /@ equation is what you want. $\endgroup$
    – luyuwuli
    Commented Apr 3, 2014 at 13:01

2 Answers 2

1
$\begingroup$

Using replacement rules in the following fashion:

NSolve[x + parameter == 0, x] /. parameter -> {1, 2, 3, 4, 5}

gives you:

{{x -> {-1, -2, -3, -4, -5}}}
$\endgroup$
3
  • 1
    $\begingroup$ Only potential caveat: This actually calls Solve rather than NSolve. $\endgroup$
    – Yves Klett
    Commented Apr 3, 2014 at 5:52
  • $\begingroup$ Can you further explain that? $\endgroup$
    – Sascha
    Commented Apr 3, 2014 at 14:28
  • $\begingroup$ You are solving for generic parameter. NSolve notices symbolic content and passes onto Solve, which returns the generic solution. The value replacement is done after that. You can see that exact numbers are returned, where NSolve would return a machine precision solution (as e.g. in my solution). Those are two quite different paths evaluation-wise, and depending on the complexity of the expression, results may vary. $\endgroup$
    – Yves Klett
    Commented Apr 3, 2014 at 18:37
1
$\begingroup$

Try this:

NSolve[x + # == 0, x] & /@ {1, 2, 3, 4}
x /. %
Flatten[%]

{{{x -> -1.}}, {{x -> -2.}}, {{x -> -3.}}, {{x -> -4.}}}

{{-1.}, {-2.}, {-3.}, {-4.}}

{-1., -2., -3., -4.}

$\endgroup$
1
  • $\begingroup$ What if I have multiple parameters? Not just one # $\endgroup$ Commented Apr 12, 2014 at 2:55

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.