root finding

Secant method

/*

to compile gcc secant.c -lm

This code is to find root of a given function by SECANT method

THIS METHOD IS USEFUL WHERE THE SLOPE IS PARRALEL TO X AXIS

( that is where Newton-Raphson fails ) AND the root is where the slope lies.

See note and figures for more insight..

*/

#include <stdio.h>

#include <math.h>

/*========================================================*/

main()

{

double f0,f1,f2,x0,x1,x2;

int i;

double func(double);

/*================================================*/

x0 = 2.0;

x1 = 2.7;

/* here we need two initial guesses x0 and x1, and the root may be NOT inside those two points */

for(i=1; i<=50; i=i+1)

{

f0 = func(x0);

f1 = func(x1);

x2 = (x0*f1-x1*f0)/(f1-f0);

f2 = func(x2);

printf("%d %f %f\n",i,x1,x2);

f0 = f1;

f1 = f2;

x0 = x1;

x1 = x2;

}

return(0);

}

/*=============================================*/

double func(double x)

{

double fn;

fn=(sin(x)/x)*(sin(x)/x);

return(fn);

}

/*=====================================*/

Root by Newton Raphson method

/* This code is to find root of a given function

by newton rapson method */

#include <stdio.h>

#include <math.h>

/*================================================================*/

main()

{

double fn,fnd,x1,x2;

int i;

double eps=0.00010;

/*================================================================*/

x1=0.0;

for(i=1; i<=100; i=i+1)

{

fn = x1*x1*x1 -2.0*x1 -5.0;

fnd = 3*x1*x1 -2.0; /* fnd is differentiation of fn with respect to x*/

x2 = x1 - fn/fnd;

printf("%d %f %f\n",i,x1,x2);

x1 = x2;

}

return(0);

}

/*================================================================*/

Finding root by Bisection method

#include <stdio.h>

#include <math.h>

/*================================================================*/

main()

{

double a = 2.0, b = 4.0;

double x0;

int i;

double eps=0.0000010;

double fn;

double func(double);

/*================================================================*/

fn = func(a)*func(b);

printf("%f %f\n",fn,func(a)*func(b));

if(func(a)*func(b)<0.0)

printf("root is inside a %f and b %f\n",a,b);

else printf("root is outside a %f and b %f \n",a,b);

for(i=1; i<=100; i++)

{ /*start for loop*/

x0 = (a+b)/2.0;

printf(" x0 = %0.20f \n",x0);

if(func(x0)*func(a) < 0.0)

/* printf("root inside a and x0\n");*/

{

a = a;

b = x0;

}

else if(func(x0)*func(b) < 0.0)

/* printf("root is inside x0 and b\n");*/

{

a = x0;

b = b;

}

} /*start for loop*/

return(0);

} /* end main code */

/*================================================================*/

double func(double x)

{

double fn;

fn=sin(x)/x;

return(fn);

}

/*================================================================*/