-
Notifications
You must be signed in to change notification settings - Fork 21
/
Bisection_Method.c
118 lines (102 loc) · 2.37 KB
/
Bisection_Method.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//Bisection Method (Without Allowed Error Concept)
#include<stdio.h>
float findValueAt(float x)
{
return x*x*x - 2*x -5;
}
float bisect(float x1,float x2)
{
return (x1+x2)/2;
}
int main()
{
int maxIteration,i=1;
float x1,x2,x;
printf("Enter Maximum no of Iterations\n");
scanf("%d",&maxIteration);
//......Compute x1 and x2.............
do
{
printf("Enter the value of x1 and x2(starting boundary)");
scanf("%f%f",&x1,&x2);
if(findValueAt(x1)*findValueAt(x2)>0)
{
printf("Roots are Invalid\n");
continue;
}
else
{
printf("Roots Lie between %f and %f\n",x1,x2);
break;
}
} while(1);
//..........Find root............
//x1 x2 ->finalised
while(i<=maxIteration)
{
x = bisect(x1,x2); //find the mid point
if(findValueAt(x)*findValueAt(x1)<0)
x2=x; //x2 is shifted
else if(findValueAt(x)*findValueAt(x2)<0)
x1=x; //x1 is shifted
printf("Iterations=%d Roots=%f\n",i,x);
i++;
}
printf("Root=%f Total Iterations=%d",x,--i);
return 0;
}
//Bisection Method (With Allowed Error Concept)
#include<stdio.h>
#include<math.h>
#define EPSILON 0.0001
float findValueAt(float x)
{
return x*x*x - 2*x -5;
}
float bisect(float x1,float x2)
{
return (x1+x2)/2;
}
int main()
{
int maxIteration,i=1;
float x1,x2,x3,x;
printf("Enter Maximum no of Iterations\n");
scanf("%d",&maxIteration);
do
{
printf("Enter the value of x1 and x2(starting boundary->Initial Roots)");
scanf("%f%f",&x1,&x2);
if(findValueAt(x1)*findValueAt(x2)>0)
{
printf("Roots are Invalid\n");
continue;
}
else
{
printf("Roots Lie between %f and %f\n",x1,x2);
break;
}
} while(1);
//find the mid point
x = bisect(x1,x2);
do
{
if(findValueAt(x)*findValueAt(x1)<0)
x2=x;
else
x1=x;
printf("Iterations=%d Roots=%f\n",i,x);
x3 = bisect(x1,x2);
if(fabs(x3-x)<EPSILON)
{
//print root
printf("Root=%f Total Iterations=%d",x,i);
return 0;
}
x=x3; //v.imp
i++;
}while(i<=maxIteration);
printf("Root=%f Total Iterations=%d",x,--i);
return 0;
}