C Program: Newton-Raphson Method

The Newton-Raphson Method, or simply Newton's Method, is a technique of finding a solution to an equation in one variable $f(x) = 0$ with the means of numerical approximation.

It finds the solution by carrying out the iteration

c program newton raphson

$x_{1} = x_{0} - \frac{f(x_{0})}{f{\prime}(x_{0})}$

where $x_{0}$ is the first approximate value, then,

$x_{2} = x_{1} - \frac{f(x_{1})}{f{\prime}(x_{1})}$

and so on.

So if $x_{n}$ is the current estimated value, the next approximation $x_{n+1}$ is given by

$x_{n+1} = x_{n} - \frac{f(x_{n})}{f{\prime}(x_{n})}$

Using the Newton-Raphson method, we will next write a C program to find an approximate value of $\sqrt{5}$. Remember, $\sqrt{5}$ is an irrational, and its decimal expansion do not end. So its exact value we can never get.

The get the approximate value of $\sqrt{5}$, the function we need is

$f(x) = x^{2} - 5$

so that, solving for

$f(x) = 0$

is the same as solving for

$x^{2} - 5 = 0$

or

$x = \sqrt{5}$

The derivative of the function is

$f{\prime}(x) = 2x$

In our program below, we define two funtions, f() and derivative(), which returns the function and its derivative respectively. The iteration is performed inside the while loop.

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

				float f(float);
				float derivative(float);

				int main() {
					float x; // x: approximation
					unsigned short i = 1, n; // n: number of iterations

					printf("FIRST APPROXIMATION: ");
					scanf("%f", &x);

					printf("ITERATIONS: ");
					scanf("%hu", &n);

					while(i <= n) {
						x = x - f(x)/derivative(x);
						i++;
					}

					printf("APPROXIMATE ROOT: %f \n", x);
					return 0;
				}

				float f(float x) { // f(x)
					return pow(x,2) - 5;
				}

				float derivative(float x) { // f'(x)
					return 2*x;
				}
				
			

We run the program with $x_{0} = 2$ as the first approximation, upto $5$ iterations

				
					$ ./a.out
					FIRST APPROXIMATION: 2
					ITERATIONS: 5
				
			

The output is

c program newton raphson for root 5