-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBisectionMethod.cs
99 lines (61 loc) · 2.44 KB
/
BisectionMethod.cs
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
namespace Bisection{
public class program{
public static double input(){
double input = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter A Bracketing Number");
return input;
}
public static double f(double num){
sealed int COEFF_DEG_3 = 1; //Coefficient of x^3
sealed int COEFF_DEG_2 = 4; //Coefficient of x^2
sealed int COEFF_DEG_0 = -10; //Coefficient of x^0
return (COEFF_DEG_3 * Math.Pow(num, 3) + COEFF_DEG_2 * Math.Pow(num, 2) + COEFF_DEG_0 * Math.Pow(num, 0));
}
public static double bisectionMethod(double f_of_a, double f_of_b, double a, double b){
double c;
double f_of_c;
sealed double tolerance = 0.0001;
while(Math.Abs(a - b) > tolerance){
c = (a + b) / 2;
f_of_c = f(c);
if(f_of_c * f(a) == 0 || f_of_c * f(b) == 0)
return c;
else if(f_of_c * f(a) > 0)
a = c;
else
b = c;
}
return (a + b) / 2;
}
public static int poly_input(int degree){
Console.WriteLine("Please Enter Coefficient For Degree " + degree);
int input = Convert.ToInt32(Console.ReadLine());
int coefficient = input;
return coefficient;
}
public static void Main(){
double a,b,c;
double f_of_a,f_of_b;
int highestDegree;
Console.WriteLine("What Is The Highest Degree Of Your Polynomial? ");
int input = Convert.ToInt32(Console.ReadLine());
highestDegree = input;
for(int i = highestDegree; i => 0; i--){
int coeff_deg_i;
coeff_deg_i = poly_input(i);
Console.WriteLine(coeff_deg_i);
}
do {
a = input();
b = input();
if(f(a) * f(b) => 0){
Console.WriteLine("Sorry the two numbers are not bracketing the root. Please try again.");
}
}while(f(a) * f(b) => 0);
f_of_a = f(a);
f_of_b = f(b);
double root = bisectionMethod(f_of_a, f_of_b, a, b );
Console.WriteLine("Root is: " + root);
}
}
}