Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
1  
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. –  luyuwuli Apr 3 at 13:01

2 Answers 2

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}}}
share|improve this answer
1  
Only potential caveat: This actually calls Solve rather than NSolve. –  Yves Klett Apr 3 at 5:52
    
Can you further explain that? –  Sascha Apr 3 at 14:28
    
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. –  Yves Klett Apr 3 at 18:37

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.}

share|improve this answer
    
What if I have multiple parameters? Not just one # –  user1886681 Apr 12 at 2:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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