Approximate Roots Using Newton's Method in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to approximate the roots of a function using Newton's method in C. The lab covers the following steps:

First, you will define the function f(x) and its derivative f'(x). Then, you will implement the iterative formula of Newton's method to calculate the approximate root. Finally, you will print the resulting approximate root.

This lab provides a practical example of applying numerical methods to solve mathematical problems using C programming. By the end of the lab, you will have a better understanding of how to use Newton's method to find the roots of a function.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435133{{"`Approximate Roots Using Newton's Method in C`"}} c/variables -.-> lab-435133{{"`Approximate Roots Using Newton's Method in C`"}} c/for_loop -.-> lab-435133{{"`Approximate Roots Using Newton's Method in C`"}} c/math_functions -.-> lab-435133{{"`Approximate Roots Using Newton's Method in C`"}} end

Define f(x) and f'(x)

In this step, we will define the mathematical function f(x) and its derivative f'(x) for implementing Newton's method to approximate roots.

First, let's create a new C file in the ~/project directory:

cd ~/project
nano newton_method.c

Now, let's write the initial code to define our function and its derivative:

#include <stdio.h>
#include <math.h>

// Define the function f(x)
double f(double x) {
    return x * x - 4;  // Example function: f(x) = x^2 - 4
}

// Define the derivative f'(x)
double f_derivative(double x) {
    return 2 * x;  // Derivative of f(x) = 2x
}

int main() {
    printf("Function f(x) = x^2 - 4\n");
    printf("Derivative f'(x) = 2x\n");
    return 0;
}

Example output:

Function f(x) = x^2 - 4
Derivative f'(x) = 2x

Let's break down the code:

  • f(x) is defined as x^2 - 4, which has roots at x = 2 and x = -2
  • f_derivative(x) is the derivative of f(x), which is 2x
  • We'll use these functions in the next steps to implement Newton's method

Compile the code to verify:

gcc -o newton_method newton_method.c -lm
./newton_method

Iterate x_{n+1}=x_n - f(x_n)/f'(x_n)

In this step, we will implement the iterative formula for Newton's method to approximate the root of our function.

Open the previous newton_method.c file:

cd ~/project
nano newton_method.c

Update the code to include the Newton's method iteration:

#include <stdio.h>
#include <math.h>

// Previous function definitions remain the same
double f(double x) {
    return x * x - 4;
}

double f_derivative(double x) {
    return 2 * x;
}

// Newton's method implementation
double newton_method(double initial_guess, int max_iterations, double tolerance) {
    double x = initial_guess;

    for (int i = 0; i < max_iterations; i++) {
        double fx = f(x);
        double fpx = f_derivative(x);

        // Check for division by zero
        if (fabs(fpx) < tolerance) {
            printf("Derivative too close to zero. Cannot continue.\n");
            return x;
        }

        // Newton's method iteration formula
        double x_next = x - fx / fpx;

        printf("Iteration %d: x = %f\n", i + 1, x_next);

        // Check for convergence
        if (fabs(x_next - x) < tolerance) {
            return x_next;
        }

        x = x_next;
    }

    printf("Maximum iterations reached.\n");
    return x;
}

int main() {
    double initial_guess = 1.0;
    int max_iterations = 10;
    double tolerance = 1e-6;

    double root = newton_method(initial_guess, max_iterations, tolerance);

    printf("\nApproximate root: %f\n", root);
    printf("f(root) = %f\n", f(root));

    return 0;
}

Compile and run the code:

gcc -o newton_method newton_method.c -lm
./newton_method

Example output:

Iteration 1: x = 2.500000
Iteration 2: x = 2.050000
Iteration 3: x = 2.000610
Iteration 4: x = 2.000000
Iteration 5: x = 2.000000

Approximate root: 2.000000
f(root) = 0.000000

Key points about the implementation:

  • newton_method() takes an initial guess, maximum iterations, and tolerance
  • Implements Newton's method iteration formula: x_{n+1} = x_n - f(x_n) / f'(x_n)
  • Checks for convergence and potential division by zero
  • Prints intermediate iterations to show the approximation process

Print the Approximate Root

In this step, we will enhance our Newton's method implementation to provide more detailed output about the root approximation.

Open the previous newton_method.c file:

cd ~/project
nano newton_method.c

Update the code to improve root approximation output:

#include <stdio.h>
#include <math.h>

// Previous function and method definitions remain the same
double f(double x) {
    return x * x - 4;
}

double f_derivative(double x) {
    return 2 * x;
}

double newton_method(double initial_guess, int max_iterations, double tolerance) {
    double x = initial_guess;

    printf("Newton's Method Root Approximation\n");
    printf("-----------------------------------\n");
    printf("Initial Guess: %f\n", x);
    printf("Tolerance: %e\n", tolerance);
    printf("Max Iterations: %d\n\n", max_iterations);

    for (int i = 0; i < max_iterations; i++) {
        double fx = f(x);
        double fpx = f_derivative(x);

        if (fabs(fpx) < tolerance) {
            printf("Error: Derivative too close to zero.\n");
            return x;
        }

        double x_next = x - fx / fpx;

        printf("Iteration %d:\n", i + 1);
        printf("  Current x: %f\n", x_next);
        printf("  f(x): %f\n", f(x_next));
        printf("  |x_next - x|: %e\n\n", fabs(x_next - x));

        if (fabs(x_next - x) < tolerance) {
            printf("Convergence achieved!\n");
            return x_next;
        }

        x = x_next;
    }

    printf("Maximum iterations reached.\n");
    return x;
}

int main() {
    double initial_guess = 1.0;
    int max_iterations = 10;
    double tolerance = 1e-6;

    double root = newton_method(initial_guess, max_iterations, tolerance);

    printf("Final Results:\n");
    printf("-------------\n");
    printf("Approximate Root: %f\n", root);
    printf("f(root): %f\n", f(root));
    printf("Absolute Error: %e\n", fabs(f(root)));

    return 0;
}

Compile and run the code:

gcc -o newton_method newton_method.c -lm
./newton_method

Example output:

Newton's Method Root Approximation
-----------------------------------
Initial Guess: 1.000000
Tolerance: 1.000000e-06
Max Iterations: 10

Iteration 1:
  Current x: 2.500000
  f(x): 2.250000
  |x_next - x|: 1.500000e+00

Iteration 2:
  Current x: 2.050000
  f(x): 0.202500
  |x_next - x|: 4.500000e-01

... (more iterations)

Convergence achieved!

Final Results:
-------------
Approximate Root: 2.000000
f(root): 0.000000
Absolute Error: 0.000000e+00

Key improvements:

  • Added detailed iteration information
  • Displayed initial parameters
  • Showed convergence progress
  • Printed final results with absolute error

Summary

In this lab, we first defined the mathematical function f(x) and its derivative f'(x) to implement Newton's method for approximating roots. We then implemented the iterative formula x_{n+1} = x_n - f(x_n)/f'(x_n) to perform the root approximation. Finally, we will print the approximate root obtained through this process.

The key steps covered in this lab are defining the target function and its derivative, and then iteratively applying the Newton's method formula to converge to the root. This approach allows us to efficiently find the roots of various mathematical functions using C programming.

Other C Tutorials you may like