Using NSolve[] and FindRoot[]

SolvingEquationsNumerically rev.nb
Using Mathematica to Find Numerical Solutions
JRF 2/7/02
revised 6/12/02 - rjerwin

This notebook illustrates how you can use Mathematica to numerically solve algebraic equations.  We'll start off by looking at some simple polynomial equations, and then move on to a more complex transcendental equation.  The importance of doing some plotting to guide you towards a meaningful solution is emphasized.

NOTE:  While Solve[] will find solutions in symbolic form, NSolve[] is the function to use if you want numerical solutions.

First, let's try to solve a simple polynomial equation: 3x = -5.

doo = NSolve[3*x + 5 == 0, x]

Note the use of the double equals sign.  From IMSE Chapter 5, we know that the numerical answer itself is tucked away in a list.

doo1 = doo[[1, 1, 2]]

Of course, higher-order polynomial equations will give you multiple solutions.

wop = NSolve[x^4 - 7*x^3 + 2*x + 1 == 0, x]

As expected, Mathematica found four roots to this quartic equation.  Depending on the physics of your problem, you might want to discard the first two complex solutions.

wop1 = wop[[3, 1, 2]]
wop2 = wop[[4, 1, 2]]

Alternatively, you could create a list of the solutions for future easy access by using the replacement operator.  (Remember, the replacement operator /. takes a symbol, such as x, and replaces it with a definite value.)

wop3 = x /. wop

Many equations are a bit more complicated.  For example, you cannot get a solution to the transcendental equation Tan[x] = x in closed form.

NSolve[Tan[x] == x, x]

In general, you only want to use NSolve[] for polynomial equations.  For other equations you will want to use the FindRoot[] function, which requires an initial guess.  Mathematica will search for a numerical solution starting with the value you supply.

FindRoot[Tan[x] == x, {x, 1}]

Here we have used an initial guess of 1.  Go back and change the guess to 10.  Notice that you got a different answer.  To see why, let's plot both functions.

Plot[{Tan[x], x}, {x, 0, 12}];

Our solutions are the places where the two functions coincide.  Since the tangent function is periodic, there are an infinite number of roots.  Starting closer to another root will give you a different solution.  Plotting helps you identify good initial guesses.  By looking at the graph and making some careful guesses, find all of the solutions in the interval 0 to 5, inclusive.  You should find three roots.

You can get more information about the many options available in NSolve[] and FindRoot[] in Mathematica Help.