Friday, September 29, 2023

Bisection Method

The bisection method is a simple numerical method used to find the root of a function. It works by repeatedly bisecting an interval and then narrowing down the interval until the root is found within a desired tolerance. Here's an overview of how the bisection method works:

Start with an initial interval [a, b] such that f(a) and f(b) have opposite signs, which guarantees the existence of a root within the interval.


Compute the midpoint c of the interval: c = (a + b) / 2.


Evaluate the function at the midpoint: f(c).


Determine the new interval:If f(c) is very close to zero (i.e., within the desired tolerance), then c is the root.
If f(c) has the same sign as f(a), the new interval becomes [c, b].
If f(c) has the same sign as f(b), the new interval becomes [a, c].


Repeat steps 2-4 until the root is found or the interval becomes sufficiently small.

The bisection method guarantees convergence to a root because the interval containing the root is halved at each step. However, the rate of convergence is generally slower compared to more advanced methods like Newton's method.

It's worth noting that the bisection method assumes that the function is continuous and that there is only one root within the given interval. Also, it is important to choose a suitable initial interval and tolerance based on the behavior of the function.

Overall, the bisection method is a reliable and robust method for finding the root of a function, particularly when other methods may not be applicable or when simplicity is preferred over speed.


#include <iostream>
#include <cmath>
using namespace std;

// Define the function for which we want to find the root
double f(double x) {
return x * x - 4; // Example function: f(x) = x^2 - 4
}

// Bisection method to find the root of a function
double bisection(double a, double b, double tol) {
if (f(a) * f(b) >= 0) {
cout << "Bisection method cannot be applied. f(a) and f(b) must have opposite signs." << endl;
return NAN; // Not a number (indicating an error)
}
double c;
while ((b - a) >= tol) {
// Find midpoint
c = (a + b) / 2;
// Check if the midpoint is the root
if (f(c) == 0.0) {
return c;
}
// Decide the new interval based on the sign of f(c)
else if (f(c) * f(a) < 0) {
b = c;
} else {
a = c;
}
}
// Return the approximate root within tolerance
return (a + b) / 2;
}

int main() {
double a = 0.0; // Left endpoint of the interval
double b = 5.0; // Right endpoint of the interval
double tolerance = 0.0001; // Tolerance for the solution
double root = bisection(a, b, tolerance);
if (!isnan(root)) {
cout << "Approximate root: " << root << endl;
} else {
cout << "No root found within the given tolerance." << endl;
}
return 0;
}

No comments:

Post a Comment

N-point Star in Microsoft Visual Studio Console App

#include <windows.h> #include <cmath> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,...