Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

needs to be written in C# (12%) Newton’s method (roots). Newton’s method or Newt

ID: 3607037 • Letter: N

Question

needs to be written in C#

(12%) Newton’s method (roots). Newton’s method or Newton-Raphson method of calculating a function / a polynomial’s roots is an easy way that uses only the knowledge of ECE 114 (for loop). Write a method Newtonsmethod that calculates (or attempt to calculate) a root from an initial guess.

You need to stop the for loop or while loop when x n and xn+1 are close (for example, if their difference is less than 1.0x10-7. ) or when n is big, say bigger than 50, since you do not want to iterate forever. However, there is a validity check: you want to make sure f(x n) 0; it would make no sense if f(x n) = 100 and you call that a root.

Test your method with the polynomial x3 + x + 1 and the initial guess x = -1.; and also the polynomial x2 - 3x + 2 and the initial guess x = 0. We do not try to calculate complex roots here.

Explanation / Answer

using System.IO;
using System;

class Program
{
  
static void Main()
{
    Program pg = new Program();
    pg.NewtonsMethod(0);
}

// The function.
private float F(float x)
{
    return (x * x - 3 * x + 2);
}

// The function's derivative.
private float dFdx(float x)
{
    return (2 * x - 3);
}

// Find a root by using Newton's method.
private void NewtonsMethod(float x0)
{
    const float cutoff = 0.0000001f;
    const float tiny = 0.00001f;
    const int max_iterations = 50;
    float epsilon;
    int iterations = 0;
    do
    {
        iterations++;

        // Make sure x0 isn't on a flat spot.
        while (Math.Abs(dFdx(x0)) < tiny) x0 += tiny;

        // Calculate the next estimate for x0.
        epsilon = -F(x0) / dFdx(x0);
        x0 += epsilon;
    } while ((Math.Abs(epsilon) > cutoff) &&
            (iterations < max_iterations));
  
    // Validate the result
    if (Math.Abs(F(x0)) < cutoff) Console.WriteLine("The root is " + x0);
    else Console.WriteLine("Could not find a root");

}

}