Programming for Computations  Python pp 185208  Cite as
Solving Nonlinear Algebraic Equations
Abstract
As a reader of this book you are probably well into mathematics and often ‘‘accused’’ of being particularly good at ‘‘solving equations’’ ( a typical comment at family dinners!). However, is it really true that you, with pen and paper, can solve many types of equations? Restricting our attention to algebraic equations in one unknown x, you can certainly do linear equations: \(ax+b=0\), and quadratic ones: \(ax^{2}+bx+c=0\). You may also know that there are formulas for the roots of cubic and quartic equations too. Maybe you can do the special trigonometric equation \(\sin x+\cos x=1\) as well, but there it (probably) stops. Equations that are not reducible to one of the mentioned cannot be solved by general analytical techniques, which means that most algebraic equations arising in applications cannot be treated with pen and paper!
If we exchange the traditional idea of finding exact solutions to equations with the idea of rather finding approximate solutions, a whole new world of possibilities opens up. With such an approach, we can in principle solve any algebraic equation.
As a reader of this book you are probably well into mathematics and often ‘‘accused’’ of being particularly good at ‘‘solving equations’’ (a typical comment at family dinners!). However, is it really true that you, with pen and paper, can solve many types of equations? Restricting our attention to algebraic equations in one unknown x, you can certainly do linear equations: \(ax+b=0\), and quadratic ones: \(ax^{2}+bx+c=0\). You may also know that there are formulas for the roots of cubic and quartic equations too. Maybe you can do the special trigonometric equation \(\sin x+\cos x=1\) as well, but there it (probably) stops. Equations that are not reducible to one of the mentioned cannot be solved by general analytical techniques, which means that most algebraic equations arising in applications cannot be treated with pen and paper!
If we exchange the traditional idea of finding exact solutions to equations with the idea of rather finding approximate solutions, a whole new world of possibilities opens up. With such an approach, we can in principle solve any algebraic equation.
So, when do we really need to solve algebraic equations beyond the simplest types we can treat with pen and paper? There are two major application areas. One is when using implicit numerical methods for ordinary differential equations. These give rise to one or a system of algebraic equations. The other major application type is optimization, i.e., finding the maxima or minima of a function. These maxima and minima are normally found by solving the algebraic equation \(F^{\prime}(x)=0\) if \(F(x)\) is the function to be optimized. Differential equations are very much used throughout science and engineering, and actually most engineering problems are optimization problems in the end, because one wants a design that maximizes performance and minimizes cost.
We first consider one algebraic equation in one variable, with our usual emphasis on how to program the algorithms. Systems of nonlinear algebraic equations with many variables arise from implicit methods for ordinary and partial differential equations as well as in multivariate optimization. Our attention will be restricted to Newton’s method for such systems of nonlinear algebraic equations.
Terminology
When solving algebraic equations \(f(x)=0\), we often say that the solution x is a root of the equation. The solution process itself is thus often called root finding.
6.1 Brute Force Methods
The representation of a mathematical function \(f(x)\) on a computer takes two forms. One is a Python function returning the function value given the argument, while the other is a collection of points \((x,f(x))\) along the function curve. The latter is the representation we use for plotting, together with an assumption of linear variation between the points. This representation is also very suited for equation solving and optimization: we simply go through all points and see if the function crosses the x axis, or for optimization, test for a local maximum or minimum point. Because there is a lot of work to examine a huge number of points, and also because the idea is extremely simple, such approaches are often referred to as brute force methods. However, we are not embarrassed of explaining the methods in detail and implementing them.
6.1.1 Brute Force Root Finding
Assume that we have a set of points along the curve of a function \(f(x)\):
We want to solve \(f(x)=0\), i.e., find the points x where f crosses the x axis. A brute force algorithm is to run through all points on the curve and check if one point is below the x axis and if the next point is above the x axis, or the other way around. If this is found to be the case, we know that f must be zero in between these two x points.
Numerical algorithm
Implementation
Given some Python implementation f(x) of our mathematical function, a straightforward implementation of the above numerical algorithm looks like
(See the file brute_force_root_finder_flat.py .)
Note the nice use of setting root to None: we can simply test if root is None to see if we found a root and overwrote the None value, or if we did not find any root among the tested points.
Running this program with some function, say \(f(x)=e^{x^{2}}\cos(4x)\) (which has a solution at \(x=\frac{\pi}{8}\)), gives the root 0.392701, which has an error of \(1.9\cdot 10^{6}\). Increasing the number of points with a factor of ten gives a root with an error of \(2.4\cdot 10^{8}\).
After such a quick ‘‘flat’’ implementation of an algorithm, we should always try to offer the algorithm as a Python function, applicable to as wide a problem domain as possible. The function should take f and an associated interval \([a,b]\) as input, as well as a number of points (n), and return a list of all the roots in \([a,b]\). Here is our candidate for a good implementation of the brute force rooting finding algorithm:
(See the file brute_force_root_finder_function.py .)
This time we use another elegant technique to indicate if roots were found or not: roots is an empty list if the root finding was unsuccessful, otherwise it contains all the roots. Application of the function to the previous example can be coded as
Note that if roots evaluates to True if roots is nonempty. This is a general test in Python: if X evaluates to True if X is nonempty or has a nonzero value.
6.1.2 Brute Force Optimization
Numerical algorithm
We realize that x _{ i } corresponds to a maximum point if \(y_{i1}<y_{i}> y_{i+1}\). Similarly, x _{ i } corresponds to a minimum if \(y_{i1}> y_{i}<y_{i+1}\). We can do this test for all ‘‘inner’’ points \(i=1,\ldots,n1\) to find all local minima and maxima. In addition, we need to add an end point, i = 0 or \(i=n\), if the corresponding y _{ i } is a global maximum or minimum.
Implementation
The algorithm above can be translated to the following Python function (file brute_force_optimizer.py ):
The max and min functions are standard Python functions for finding the maximum and minimum element of a list or an object that one can iterate over with a for loop.
An application to \(f(x)=e^{x^{2}}\cos(4x)\) looks like
6.1.3 Model Problem for Algebraic Equations
In the following, we will present several efficient and accurate methods for solving nonlinear algebraic equations, both single equation and systems of equations. The methods all have in common that they search for approximate solutions. The methods differ, however, in the way they perform the search for solutions. The idea for the search influences the efficiency of the search and the reliability of actually finding a solution. For example, Newton’s method is very fast, but not reliable, while the bisection method is the slowest, but absolutely reliable. No method is best at all problems, so we need different methods for different problems.
What is the difference between linear and nonlinear equations?
You know how to solve linear equations \(ax+b=0\): \(x=b/a\). All other types of equations \(f(x)=0\), i.e., when \(f(x)\) is not a linear function of x, are called nonlinear. A typical way of recognizing a nonlinear equation is to observe that x is ‘‘not alone’’ as in ax, but involved in a product with itself, such as in \(x^{3}+2x^{2}9=0\). We say that x ^{3} and \(2x^{2}\) are nonlinear terms. An equation like \(\sin x+e^{x}\cos x=0\) is also nonlinear although x is not explicitly multiplied by itself, but the Taylor series of \(\sin x\), e ^{ x }, and \(\cos x\) all involve polynomials of x where x is multiplied by itself.
6.2 Newton’s Method
Newton’s method, also known as NewtonRaphson’s method, is a very famous and widely used method for solving nonlinear algebraic equations. Compared to the other methods we will consider, it is generally the fastest one (usually by far). It does not guarantee that an existing solution will be found, however.
A fundamental idea of numerical methods for nonlinear equations is to construct a series of linear equations (since we know how to solve linear equations) and hope that the solutions of these linear equations bring us closer and closer to the solution of the nonlinear equation. The idea will be clearer when we present Newton’s method and the secant method.
6.2.1 Deriving and Implementing Newton’s Method
How do we compute the tangent of a function \(f(x)\) at a point x _{0}? The tangent function, here called \(\tilde{f}(x)\), is linear and has two properties:
 1.
the slope equals to \(f^{\prime}(x_{0})\)
 2.
the tangent touches the \(f(x)\) curve at x _{0}
We moved from 1000 to 250 in two iterations, so it is exciting to see how fast we can approach the solution x = 3. A computer program can automate the calculations. Our first try at implementing Newton’s method is in a function naive_Newton:
The argument x is the starting value, called x _{0} in our previous mathematical description. We use float(f(x)) to ensure that an integer division does not happen by accident if f(x) and dfdx(x) both are integers for some x.
To solve the problem \(x^{2}=9\) we also need to implement
Why not use an array for the x approximations?
Such an array is fine, but requires storage of all the approximations. In large industrial applications, where Newton’s method solves millions of equations at once, one cannot afford to store all the intermediate approximations in memory, so then it is important to understand that the algorithm in Newton’s method has no more need for x _{ n } when \(x_{n+1}\) is computed. Therefore, we can work with one variable x and overwrite the previous value:
Running naive_Newton(f, dfdx, 1000, eps=0.001) results in the approximate solution 3.000027639. A smaller value of eps will produce a more accurate solution. Unfortunately, the plain naive_Newton function does not return how many iterations it used, nor does it print out all the approximations \(x_{0},x_{1},x_{2},\ldots\), which would indeed be a nice feature. If we insert such a printout, a rerun results in
We clearly see that the iterations approach the solution quickly. This speed of the search for the solution is the primary strength of Newton’s method compared to other methods.
6.2.2 Making a More Efficient and Robust Implementation
The naive_Newton function works fine for the example we are considering here. However, for more general use, there are some pitfalls that should be fixed in an improved version of the code. An example may illustrate what the problem is: let us solve \(\tanh(x)=0\), which has solution x = 0. With \(x_{0}\leq 1.08\) everything works fine. For example, x _{0} leads to six iterations if \(\epsilon=0.001\):
Adjusting x _{0} slightly to 1.09 gives division by zero! The approximations computed by Newton’s method become
The division by zero is caused by \(x_{7}=1.26055913647\cdot 10^{11}\), because \(\tanh(x_{7})\) is 1.0 to machine precision, and then \(f^{\prime}(x)=1\tanh(x)^{2}\) becomes zero in the denominator in Newton’s method.
The underlying problem, leading to the division by zero in the above example, is that Newton’s method diverges: the approximations move further and further away from x = 0. If it had not been for the division by zero, the condition in the while loop would always be true and the loop would run forever. Divergence of Newton’s method occasionally happens, and the remedy is to abort the method when a maximum number of iterations is reached.
Another disadvantage of the naive_Newton function is that it calls the \(f(x)\) function twice as many times as necessary. This extra work is of no concern when \(f(x)\) is fast to evaluate, but in largescale industrial software, one call to \(f(x)\) might take hours or days, and then removing unnecessary calls is important. The solution in our function is to store the call f(x) in a variable (f_value) and reuse the value instead of making a new call f(x).
To summarize, we want to write an improved function for implementing Newton’s method where we

avoid division by zero

allow a maximum number of iterations

avoid the extra evaluation of \(f(x)\)
A more robust and efficient version of the function, inserted in a complete program Newtons_method.py for solving \(x^{2}9=0\), is listed below.
Handling of the potential division by zero is done by a tryexcept construction. Python tries to run the code in the try block. If anything goes wrong here, or more precisely, if Python raises an exception caused by a problem (such as division by zero, array index out of bounds, use of undefined variable, etc.), the execution jumps immediately to the except block. Here, the programmer can take appropriate actions. In the present case, we simply stop the program. (Professional programmers would avoid calling sys.exit inside a function. Instead, they would raise a new exception with an informative error message, and let the calling code have another tryexcept construction to stop the program.)
The division by zero will always be detected and the program will be stopped. The main purpose of our way of treating the division by zero is to give the user a more informative error message and stop the program in a gentler way.
Calling sys.exit with an argument different from zero (here 1) signifies that the program stopped because of an error. It is a good habit to supply the value 1, because tools in the operating system can then be used by other programs to detect that our program failed.
To prevent an infinite loop because of divergent iterations, we have introduced the integer variable iteration_counter to count the number of iterations in Newton’s method. With iteration_counter we can easily extend the condition in the while such that no more iterations take place when the number of iterations reaches 100. We could easily let this limit be an argument to the function rather than a fixed constant.
The Newton function returns the approximate solution and the number of iterations. The latter equals −1 if the convergence criterion \(f(x)<\epsilon\) was not reached within the maximum number of iterations. In the calling code, we print out the solution and the number of function calls. The main cost of a method for solving \(f(x)=0\) equations is usually the evaluation of \(f(x)\) and \(f^{\prime}(x)\), so the total number of calls to these functions is an interesting measure of the computational work. Note that in function Newton there is an initial call to \(f(x)\) and then one call to f and one to \(f^{\prime}\) in each iteration.
Running Newtons_method.py, we get the following printout on the screen:
As we did with the integration methods in Chapter 3, we will collect our solvers for nonlinear algebraic equations in a separate file named nonlinear_solvers.py for easy import and use. The first function placed in this file is then Newton.
The Newton scheme will work better if the starting value is close to the solution. A good starting value may often make the difference as to whether the code actually finds a solution or not. Because of its speed, Newton’s method is often the method of first choice for solving nonlinear algebraic equations, even if the scheme is not guaranteed to work. In cases where the initial guess may be far from the solution, a good strategy is to run a few iterations with the bisection method (see Chapter 6.4) to narrow down the region where f is close to zero and then switch to Newton’s method for fast convergence to the solution.
Newton’s method requires the analytical expression for the derivative \(f^{\prime}(x)\). Derivation of \(f^{\prime}(x)\) is not always a reliable process by hand if \(f(x)\) is a complicated function. However, Python has the symbolic package SymPy, which we may use to create the required dfdx function. In our sample problem, the recipe goes as follows:
The nice feature of this code snippet is that dfdx_expr is the exact analytical expression for the derivative, 2*x, if you print it out. This is a symbolic expression so we cannot do numerical computing with it, but the lambdify constructions turn symbolic expressions into callable Python functions.
The next method is the secant method, which is usually slower than Newton’s method, but it does not require an expression for \(f^{\prime}(x)\), and it has only one function call per iteration.
6.3 The Secant Method
We can store the approximations x _{ n } in an array, but as in Newton’s method, we notice that the computation of \(x_{n+1}\) only needs knowledge of x _{ n } and \(x_{n1}\), not ‘‘older’’ approximations. Therefore, we can make use of only three variables: x for \(x_{n+1}\), x1 for x _{ n }, and x0 for \(x_{n1}\). Note that x0 and x1 must be given (guessed) for the algorithm to start.
A program secant_method.py that solves our example problem may be written as:
The number of function calls is now related to no_iterations, i.e., the number of iterations, as 2 + no_iterations, since we need two function calls before entering the while loop, and then one function call per loop iteration. Note that, even though we need two points on the graph to compute each updated estimate, only a single function call (f(x1)) is required in each iteration since f(x0) becomes the ‘‘old’’ f(x1) and may simply be copied as f_x0 = f_x1 (the exception is the very first iteration where two function evaluations are needed).
Running secant_method.py, gives the following printout on the screen:
As with the function Newton, we place secant in the file nonlinear_solvers. py for easy import and use later.
6.4 The Bisection Method
Neither Newton’s method nor the secant method can guarantee that an existing solution will be found (see Exercises 6.1 and 6.2). The bisection method, however, does that. However, if there are several solutions present, it finds only one of them, just as Newton’s method and the secant method. The bisection method is slower than the other two methods, so reliability comes with a cost of speed.
To solve \(x^{2}9=0\), \(x\in\left[0,1000\right]\), with the bisection method, we reason as follows. The first key idea is that if \(f(x)=x^{2}9\) is continuous on the interval and the function values for the interval endpoints (\(x_{L}=0\), \(x_{R}=1000\)) have opposite signs, \(f(x)\) must cross the x axis at least once on the interval. That is, we know there is at least one solution.
The second key idea comes from dividing the interval in two equal parts, one to the left and one to the right of the midpoint \(x_{M}=500\). By evaluating the sign of \(f(x_{M})\), we will immediately know whether a solution must exist to the left or right of x _{ M }. This is so, since if \(f(x_{M})\geq 0\), we know that \(f(x)\) has to cross the x axis between x _{ L } and x _{ M } at least once (using the same argument as for the original interval). Likewise, if instead \(f(x_{M})\leq 0\), we know that \(f(x)\) has to cross the x axis between x _{ M } and x _{ R } at least once.
In any case, we may proceed with half the interval only. The exception is if \(f(x_{M})\approx 0\), in which case a solution is found. Such interval halving can be continued until a solution is found. A ‘‘solution’’ in this case, is when \(f(x_{M})\) is sufficiently close to zero, more precisely (as before): \(f(x_{M})<\epsilon\), where ϵ is a small number specified by the user.
The sketched strategy seems reasonable, so let us write a reusable function that can solve a general algebraic equation \(f(x)=0\) ( bisection_method.py ):
Note that we first check if f changes sign in \([a,b]\), because that is a requirement for the algorithm to work. The algorithm also relies on a continuous \(f(x)\) function, but this is very challenging for a computer code to check.
We get the following printout to the screen when bisection_method.py is run:
We notice that the number of function calls is much higher than with the previous methods.
Required work in the bisection method
As with the two previous methods, the function bisection is placed in the file nonlinear_solvers.py for easy import and use.
6.5 Rate of Convergence
Therefore, we have extended the implementations in the module file nonlinear_solvers.py such that the user can choose whether the final value or the whole history of solutions is to be returned. Each of the extended implementations now takes an extra parameter return_x_list. This parameter is a boolean, set to True if the function is supposed to return all the root approximations, or False, if the function should only return the final approximation. As an example, let us take a closer look at Newton:
The function is found in the file nonlinear_solvers.py .
We can now make a call
and get a list x returned. With knowledge of the exact solution x of \(f(x)=0\) we can compute all the errors e _{ n } and all the associated q _{ n } values with the compact function
The error model (6.5) works well for Newton’s method and the secant method. For the bisection method, however, it works well in the beginning, but not when the solution is approached.
We can compute the rates q _{ n } and print them nicely,
The result for print_rates(’Newton’, x, 3) is
indicating that q = 2 is the rate for Newton’s method. A similar computation using the secant method, gives the rates
Here it seems that \(q\approx 1.6\) is the limit.
Remark
If we in the bisection method think of the length of the current interval containing the solution as the error e _{ n }, then (6.5) works perfectly since \(e_{n+1}=\frac{1}{2}e_{n}\), i.e., q = 1 and \(C=\frac{1}{2}\), but if e _{ n } is the true error \(xx_{n}\), it is easily seen from a sketch that this error can oscillate between the current interval length and a potentially very small value as we approach the exact solution. The corresponding rates q _{ n } fluctuate widely and are of no interest.
6.6 Solving Multiple Nonlinear Algebraic Equations
So far in this chapter, we have considered a single nonlinear algebraic equation. However, systems of such equations arise in a number of applications, foremost nonlinear ordinary and partial differential equations. Of the previous algorithms, only Newton’s method is suitable for extension to systems of nonlinear equations.
6.6.1 Abstract Notation
6.6.2 Taylor Expansions for MultiVariable Functions
We follow the ideas of Newton’s method for one equation in one variable: approximate the nonlinear f by a linear function and find the root of that function. When n variables are involved, we need to approximate a vector function \(\boldsymbol{F}(\boldsymbol{x})\) by some linear function \(\tilde{\boldsymbol{F}}=\boldsymbol{J}\boldsymbol{x}+\boldsymbol{c}\), where J is an \(n\times n\) matrix and c is some vector of length n.
The matrix \(\nabla\boldsymbol{F}\) is called the Jacobian of F and often denoted by J.
6.6.3 Newton’s Method
The ith iteration of Newton’s method for systems of algebraic equations consists of two steps:
 1.
Solve the linear system \(\boldsymbol{J}(\boldsymbol{x}_{i})\boldsymbol{\delta}=\boldsymbol{F}(\boldsymbol{x}_{i})\) with respect to \(\boldsymbol{\delta}\).
 2.
Set \(\boldsymbol{x}_{i+1}=\boldsymbol{x}_{i}+\boldsymbol{\delta}\).
Solving systems of linear equations must make use of appropriate software. Gaussian elimination is the most common, and in general the most robust, method for this purpose. Python’s numpy package has a module linalg that interfaces the wellknown LAPACK package with highquality and very well tested subroutines for linear algebra. The statement x = numpy.linalg.solve(A, b) solves a system \(Ax=b\) with a LAPACK method based on Gaussian elimination.
When nonlinear systems of algebraic equations arise from discretization of partial differential equations, the Jacobian is very often sparse, i.e., most of its elements are zero. In such cases it is important to use algorithms that can take advantage of the many zeros. Gaussian elimination is then a slow method, and (much) faster methods are based on iterative techniques.
6.6.4 Implementation
Here is a very simple implementation of Newton’s method for systems of nonlinear algebraic equations:
We can test the function Newton_system with the \(2\times 2\) system (6.11)(6.12):
Here, the testing is based on the L2 norm of the error vector. Alternatively, we could test against the values of x that the algorithm finds, with appropriate tolerances. For example, as chosen for the error norm, if eps=0.0001, a tolerance of \(10^{4}\) can be used for x[0] and x[1].
6.7 Exercises
Exercise 6.1 (Understand why Newton’s method can fail)
The purpose of this exercise is to understand when Newton’s method works and fails. To this end, solve \(\tanh x=0\) by Newton’s method and study the intermediate details of the algorithm. Start with \(x_{0}=1.08\). Plot the tangent in each iteration of Newton’s method. Then repeat the calculations and the plotting when \(x_{0}=1.09\). Explain what you observe.
Filename: Newton_failure.*.
Exercise 6.2 (See if the secant method fails)
 1.
\(x_{0}=1.08\) and \(x_{1}=1.09\)
 2.
\(x_{0}=1.09\) and \(x_{1}=1.1\)
 3.
\(x_{0}=1\) and \(x_{1}=2.3\)
 4.
\(x_{0}=1\) and \(x_{1}=2.4\)
Filename: secant_failure.*.
Exercise 6.3 (Understand why the bisection method cannot fail)
Solve the same problem as in Exercise 6.1, using the bisection method, but let the initial interval be \([5,3]\). Report how the interval containing the solution evolves during the iterations.
Filename: bisection_nonfailure.*.
Exercise 6.4 (Combine the bisection method with Newton’s method)
An attractive idea is to combine the reliability of the bisection method with the speed of Newton’s method. Such a combination is implemented by running the bisection method until we have a narrow interval, and then switch to Newton’s method for speed.
Write a function that implements this idea. Start with an interval \([a,b]\) and switch to Newton’s method when the current interval in the bisection method is a fraction s of the initial interval (i.e., when the interval has length \(s(ba)\)). Potential divergence of Newton’s method is still an issue, so if the approximate root jumps out of the narrowed interval (where the solution is known to lie), one can switch back to the bisection method. The value of s must be given as an argument to the function, but it may have a default value of 0.1.
Try the new method on \(\tanh(x)=0\) with an initial interval \([10,15]\).
Filename: bisection_Newton.py.
Exercise 6.5 (Write a test function for Newton’s method)
The purpose of this function is to verify the implementation of Newton’s method in the Newton function in the file nonlinear_solvers.py. Construct an algebraic equation and perform two iterations of Newton’s method by hand or with the aid of SymPy. Find the corresponding size of \(f(x)\) and use this as value for eps when calling Newton. The function should then also perform two iterations and return the same approximation to the root as you calculated manually. Implement this idea for a unit test as a test function test_Newton().
Filename: test_Newton.py.
Exercise 6.6 (Solve nonlinear equation for a vibrating beam)
 a)
Plot the equation to be solved so that one can inspect where the zero crossings occur.
Hint
When writing the equation as \(f(\beta)=0\), the f function increases its amplitude dramatically with β. It is therefore wise to look at an equation with damped amplitude, \(g(\beta)=e^{\beta}f(\beta)=0\). Plot g instead.
 a)
Compute the first three frequencies.
Filename: beam_vib.py.
Footnotes
Copyright information
Open Access This chapter is distributed under the terms of the Creative Commons Attribution‐NonCommercial 4.0 International License (http://creativecommons.org/licenses/bync/4.0/), which permits any noncommercial use, duplication, adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, a link is provided to the Creative Commons license and any changes made are indicated.
The images or other third party material in this chapter are included in the work’s Creative Commons license, unless indicated otherwise in the credit line; if such material is not included in the work’s Creative Commons license and the respective action is not permitted by statutory regulation, users will need to obtain permission from the license holder to duplicate, adapt or reproduce the material.