-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbisection_method.cpp
More file actions
45 lines (35 loc) · 1.02 KB
/
bisection_method.cpp
File metadata and controls
45 lines (35 loc) · 1.02 KB
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
#include <iostream>
#include <cmath>
double function(double x) {
// Define your function here
return x * x - 4*x-10;
}
double bisection(double a, double b, double tolerance) {
if (function(a) * function(b) >= 0) {
std::cout << "Bisection method cannot guarantee convergence for the given interval." << std::endl;
return 0.0;
}
double c = a;
while ((b - a) >= tolerance) {
c = (a + b) / 2;
if (function(c) == 0.0) {
break;
} else if (function(c) * function(a) < 0) {
b = c;
} else {
a = c;
}
}
return c;
}
int main() {
double a, b, tolerance;
std::cout << "Enter the initial interval [a, b]: ";
std::cin >> a >> b;
std::cout << "Enter the tolerance: ";
std::cin >> tolerance;
double root = bisection(a, b, tolerance);
std::cout << "Approximate root: " << root << std::endl;
std::cout << "Function value at the approximate root: " << function(root) << std::endl;
return 0;
}