Open c05ax_demo.m in the Editor
Run demo

The C05 chapter - Finding the root of an equation

We start with the calculation of the zeros of a continuous function. The C05 chapter contains several routines for doing this (as well as other routines which solve a set of nonlinear equations in several unknowns). In our first example, we solve a quadratic equation.

25x2 - 10x + 1 = 0

Of course, it is trivial to determine analytically that both roots are at x = 0.2 (which provides a handy check on our numerical result - see below) but the C05 routines can be used to find the zeros of any function, as long as it is continuous. Here, we use routine c05ax; this evaluates the function via reverse communication, which allows us to display the intermediate results on the way to finding the root.

Here's the code, including some plotting commands:

   
% Specify the function as a MATLAB anonymous function - this facilitates
% changing the function for other examples.
myfun = @(x)25*x*x - 10*x + 1;

% Specify the initial estimate of the zero, and the value of the function
% there (the latter is only needed for plotting).
xstart = 1.0;
fstart = myfun(xstart);
xx = xstart;
fx = fstart;

% Specify other parameters for the NAG routine.  tol is the tolerance, 
% used by the routine to control the accuracy of the solution.
tol = 0.00001;
ir = nag_int(0);
c = zeros(26, 1);
ind = nag_int(1);

% Iterate until the solution is reached.
while (ind ~= nag_int(0))

% Call the NAG routine to get an improved estimate of the zero, 
% then plot it.
  [xx, c, ind, ifail] = c05ax(xx, fx, tol, ir, c, ind);
  fx = myfun(xx);

  plot(axes, xx, fx, 'or', 'MarkerFaceColor', [1,0,0], 'MarkerSize', 8);
  
end

% Plot initial estimate, and final solution.
plot(axes, xstart, fstart, 'og', 'MarkerFaceColor', [0,1,0], 'MarkerSize', 8);
plot(axes, xx, fx, 'oy', 'MarkerFaceColor', [1,1,0], 'MarkerSize', 8);

and the results are shown in this picture:


Figure 1: Finding the root of a quadratic.

As a second example, we can use the same code to find the root of a different function (for example, one that is harder to determine analytically) by changing the first few lines of the code above to:

   
% Specify the function as a MATLAB anonymous function - this facilitates
% changing the function for other examples.
myfun = @(x)x - exp(-x);

% Specify the initial estimate of the zero, and the value of the function
% there (the latter is only needed for plotting).
xstart = 5.0;

giving the results shown in Figure 2.


Figure 2: Finding the root of a transcendental function.