Saturday, August 25, 2007

Iterative methods in C (Bisection Method, False Position, Newton Raphson, Secant)

Iterative methods in C (Bisection Method, False Position, Newton Raphson, Secant)

Bisection Method
=================

#include <stdio.h>
#include <math.h>
#include <conio.h>
#define EPSILON 0.0001
#define f(x) (x*x*x-4*x-9)
void main ()
{
double x1,x2,x3,x;
clrscr ();
printf("Enter the values between the root of the equation lies:\n");
scanf ("%lf %lf",&x1,&x2);
do
{
x3 = (x1 + x2)/2;
if ((f(x1) * f(x3)) < 0)
x2 = x3;
else
x1 = x3;
} while (labs(x1 - x2) > EPSILON && f(x3) != 0);
printf("The root is %lf",x3);
getch ();
}


False Position
==============

#include <stdio.h>
#include <conio.h>
#include <math.h>
#define EPSILON 0.0001
#define f(x) (x*x*x - 2*x - 5)
void main ()
{
float x1,x2,x3,x,f1,f2,f3;
clrscr ();
printf("Enter the points between which the root lies:\n");
scanf ("%f %f",&x1,&x2);
f1 = f(x1);
f2 = f(x2);
if ((f1 * f2) > 0)
{
printf("Initial approximation are unsuitable");
exit (0);
}
do
{
x3 = (x1*f2 - x2*f1)/(f2 - f1);
f3 = f(x3);
if (f1 * f3 < 0)
{
x2 = x3;
f2 = f3;
}
else
{
x1 = x3;
f1 = f3;
}
} while ((labs(x1 - x2) > EPSILON) && (f3 != 0));
printf("The approximate root is %lf",x3);
getch ();
}

Newton Raphson
==============


#include <stdio.h>
#include <conio.h>
#include <math.h>
#define EPSILON 0.0001
#define f(x) (x*x*x-4*x-9)
#define df(x) (3*x*x-4)
void main ()
{
double x0,x1,x,relative_error;
int n,i;
clrscr ();
printf("Enter the value of x0: ");
scanf("%lf",&x0);
printf("Enter the number of iterations you want to perform: ");
scanf ("%d",&n);
for (i=0;i<n;i++)
{
x1 = x0-f(x0)/df(x0);
relative_error = labs((x1-x0)/x1);
x0 = x1;
if((relative_error <= EPSILON) (f(x1) == 0))
{
printf("%lf as the approximate root",x1);
exit (1);
}
}
printf("Solution does not converge in %d iterations");
getch ();
}

Secant
========


#include <stdio.h>
#include <conio.h>
#include <math.h>
#define EPSILON 0.0001
#define f(x) (cos(x) - x*exp(x))
void main ()
{
double x1,x2,x3,x,epsilon,f1,f2,f3;
int n,i;
clrscr ();
printf ("Enter the value of the two points:\n");
scanf ("%lf %lf",&x1, &x2);
printf("Enter the number of iterations do you want to perform: ");
scanf("%d",&n);
f1 = f(x1);
f2 = f(x2);
for (i=0;i<n;i++)
{
x3 = (x1*f2 - x2*f1)/(f2 - f1);
f3 = f(x3);
if ((labs((x3-x2)/x3)) <= EPSILON (f(x1) == 0))
{
printf("The approximate root is %lf",x3);
exit (1);
}
x1 = x2;
f1 = f2;
x2 = x3;
f2 = f3;
}
printf("Solution does not coverage in %d iterations",n);
}

No comments: