So far, we have been looking at various codes
that we wrote for Newton's method and bisection.
Now, let's look at MATLAB's built-in command fzero
for finding the root of a continuous scalar
valued function in one-dimension.
So we'll see that the inputs fun is
going to be a function handle to your objective function,
x0 is going to be our initial guess,
and options will contain a structure
of various options such as your convergence criteria.
The output, first output, is going
to be the root found and then the corresponding fval
at that particular x.
So this should be approximately zero
if your algorithm has converged within the given tolerance.
The exitflag is your convergence flag
so this will be 1 if the algorithm converged
and negative, otherwise.
The output structure is going to be very important about telling
us the number of iterations that the solver took,
as well as number of function evaluations
and this will help us compare different methods
for different functions.
So now, let's look back at that first example.
The first case is where we have two solutions
and I'd like you to try x squared minus 1
from any initial guess away from plus or minus 1
and experiment with how the location of your initial guess
will converge to different solutions.
We're also going to try it on the unique case, x squared,
and we're also going to try it on the case x squared plus 1
where no solution exists.
So welcome back.
The solution is given in fzero_soln.m and we'll see
the first case.
Let's look at how it performs with x squared.
OK.
We'll see that it's not converging so our x1 value is
not a number, fval is 1, and our exitflag
will indicate that a problem occurred.
OK.
We're getting an exit of negative 3.
So what do we think is going wrong for the x squared case?
The gradient exists and there is a unique solution
at x is equal to zero.
Recall that fzero is using bisection and secant based
methods so it's not taking the gradient into account.
In particular, what bisection does
is it looks at the sign of our function values,
but in this expert example, there's
no sign change on that interval, meaning that any method using
bisection will not work here.
We'll need a Newton based derivative method
for this problem.
OK.
Now, let's look at the x squared minus 1 case.
Here, you will see that we've converged to the solution x
is equal to 1.
This is because we're starting an initial guess 4.
Let's say, I started at negative 4.
Now, we'll see x2 given by negative 1.
If we look at the corresponding function value, it should be 0
and our exit flag is marked as 1.
Now what about in the case where no solution exists?
Here, we do want the algorithm to fail because there
is no solution to this problem.
So we'll see the limits of fzero occurring
in the f of x is equal to x squared case
where there was no sign change within your function.