4. Newton's method

This program's FindRoots method is almost the same as the version used by the preceding solution. The only difference is that the new version calls the following method instead of the BinarySubdivision method:

// Search this interval for a root.
private double NewtonsMethod(
Func<double, double> F, Func<double, double> FPrime,
double x, double maxError, double maxTrials)
{
for (int trial = 0; trial < maxTrials; trial++)
{
x = x - F(x) / FPrime(x);
double y = F(x);
double error = Math.Abs(y);
if (error < maxError) return x;
}
return double.NaN;
}

Because this method uses a single variable, x, to keep track of its current estimate for the root, it does not need to check that an interval's endpoints lie on opposite sides of the X axis the way the BinarySubdivision method does. Instead, it simply enters a loop where it uses the equation in the problem statement to update x. When F(x) is close enough to zero, the method returns x.

One place where this method differs from the BinarySubdivision method is that it only performs its loop at most maxTrials times. Under certain conditions that depend on the function being studied, Newton's method may produce a sequence of repeating or diverging values that don't converge to a root. Limiting the loop prevents the program from being stuck in an infinite loop.

Newton's method converges very quickly, so the example solution sets maxTrials to only 1,000. After 1,000 trials, the method has either already found a root or it is probably not converging.

The NewtonsMethod example solution looks the same as the BinarySubdivisionRoots program shown in the earlier screenshot, so I won't show it here. Download the example to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.118