-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall_possible_roots.cpp
90 lines (85 loc) · 1.75 KB
/
all_possible_roots.cpp
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
#include <bits/stdc++.h>
using namespace std;
int coef[100] = {0};
double roots[100];
int max_power;
double error;
int flag = 0, co;
void All_possible_roots(double p,double q,double delx);
double fx(double x0);
double bi_section(double x1, double x2);
int main()
{
double p,q,ans,delx;
printf("Enter the maximum power : ");
scanf("%d",&max_power);
for(int i = 0 ; i <= max_power ;i++)
{
printf("Co-efficient of x%d = ",i);
scanf("%d",&coef[i]);
}
printf("Enter the lower limit : ");
scanf("%lf",&p);
printf("Enter the upper limit : ");
scanf("%lf",&q);
printf("Enter error : ");
scanf("%lf",&error);
printf("Input delX : ");
scanf("%lf", &delx);
All_possible_roots(p,q,delx);
if(flag == 1)
{
printf("X1 and X2 do not bracket any root.\n\n");
}
else
{
for(int i = 0 ; i < co ; i++)
{
printf("%lf ",roots[i]);
}
}
}
void All_possible_roots(double p , double q, double delx)
{
int co = 0;
double x1 = p;
double x2 = p+delx;
while(x2 < q)
{
if(fx(x1)*fx(x2) > 0)
{
flag = 1;
return ;
}
else if(fx(x1)*fx(x2) < 0)
{
roots[co++] = bi_section(x1,x2);
}
x1 = x2;
x2 = x2+delx;
}
}
double bi_section(double x1, double x2)
{
double x0;
do{
x0 = (x1+x2)/2.0;
if(fx(x0) == 0)
return x0;
if(fx(x0)*fx(x1)< 0)
x2 = x0;
else x1 = x0;
if(fabs((x2-x1)/x2) <= error)
return x0;
}while(fabs((x2-x1)/x2) > error);
}
double fx(double x0)
{
double fx1 = 0;
for(int i=max_power;i>=1;i--)
{
fx1+=coef[i] * (pow(x0,i)) ;
}
fx1+=coef[0];
return fx1;
}