BISECTION METHOD
July 22, 2022
Finding The Roots Of The Given Equation By Using Bisection Method
Source code :-
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
float f(float x)
{
return (x * x * x - 3 * x + 1.06); // Replace With given Equation
}
int main()
{
float a, b, x, y, err;
int n = 0, d;
printf("Enter the lower limit: ");
scanf("%f", &a);
printf("\nEnter the upper limit: ");
scanf("%f", &b);
if (f(a) * f(b) > 0)
{
printf("\nRoot does not exists between %f and %f\n", a, b);
exit(0);
}
// We consider "f(a)" as (+ve) and "f(b)" as (-ve)
if (f(a) < 0 && f(b) > 0) // swap the values of a and b.
{
y = b;
b = a;
a = y;
}
printf("\nEnter the correction upto decimal place: ");
scanf("%d", &d);
err = (5.0 / pow(10, d));
printf("\n\n N\tAn(+ve) \tBn(-ve) \tXn+1(An+Bn)/2 \tf(Xn+1)\n");
printf("\n----------------------------------------------------------------\n");
// Consider the initial root is 0
x = 0;
do
{
y = x;
x = (a + b) / 2;
printf("\n %2d \t%2.5f \t%2.5f \t%2.5f \t%+2.5f\n", ++n, a, b, x, f(x));
if (f(x) > 0)
a = x;
else
b = x;
} while (fabs(x - y) >= err);
printf("\n\n\t\t\tThe root is: x=%f\n\n\n", x);
return 1;
}
Input-Output :-
abhi@hp-15q-laptop:~$ gcc bisection.cabhi@hp-15q-laptop:~$ ./a.out
Enter the lower limit: 0
Enter the upper limit: 1
Enter the correction upto decimal place: 5
N An(+ve) Bn(-ve) Xn+1(An+Bn)/2 f(Xn+1)
----------------------------------------------------------------
1 0.00000 1.00000 0.50000 -0.31500
2 0.00000 0.50000 0.25000 +0.32563
3 0.25000 0.50000 0.37500 -0.01227
4 0.25000 0.37500 0.31250 +0.15302
5 0.31250 0.37500 0.34375 +0.06937
6 0.34375 0.37500 0.35938 +0.02829
7 0.35938 0.37500 0.36719 +0.00794
8 0.36719 0.37500 0.37109 -0.00218
9 0.36719 0.37109 0.36914 +0.00288
10 0.36914 0.37109 0.37012 +0.00035
11 0.37012 0.37109 0.37061 -0.00091
12 0.37012 0.37061 0.37036 -0.00028
13 0.37012 0.37036 0.37024 +0.00003
14 0.37024 0.37036 0.37030 -0.00012
15 0.37024 0.37030 0.37027 -0.00005
The root is: x=0.370270