The bisection method is based on the following result from calculus:
The Intermediate Value Theorem: Assume f : IR→IR is a continuous function and there are two real numbers a and b such that f (a)f (b) < 0. Then f (x) has at least one zero between a and b.
In other words, if a continuous function has different signs at two points, it has to go through zero somewhere in between!
The bisection method consists of finding two such numbers a and b, then halving the interval [a,b] and keeping the half on which f (x) changes sign and repeating the procedure until this interval shrinks to give the required accuracy for the root.
An algorithm could be defined as follows. Suppose we need a root for f (x) = 0 and we have an error tolerance of ε (the absolute error in calculating the root must be less that ε).
Bisection Algorithm:
- Find two numbers a and b at which f has different signs.
- Define c = a+b
- If b−c ≤ε then accept c as the root and stop.
- If f (a)f (c)≤0 then set c as the new b. Otherwise, set c as the new a. Return to step 1.
Let α be the value of the root, a≤α≤b. Let an, bn and cn be the values of a, b and c on the nth iteration of the algorithm.
Then the error bound for cn is given by
|α−cn| ≤ (1/2n) (b−a)
This inequality can give us the number of iterations needed for a required accuracy ε
n ≥ ((log(b−a)/ε)) / log2
Advantages and disadvantages of the bisection method
- The method is guaranteed to converge.
- The error bound decreases by half with each iteration.
- The bisection method converges very slowly.
- The bisection method cannot detect multiple roots
Example Code:
Bisection Method x2-5
root between 2 and 3
File name : bisection.c
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<math.h> float f(float x) { return (x*x)-5; } main() { float x0,x1,x2,E; int count=1; charch; clrscr(); xyz: printf("\nEnter value of x0"); scanf("%f",&x0); printf("\nEnter value of x1"); scanf("%f",&x1); printf("\nEnter value of error interation:"); scanf("%f",&E); clrscr(); printf("\n NO\tx0\tx1\tx2\tf(x0)\tf(x1)\tf(x2)"); if(f(x0)*f(x1)<0) { x2=(x0+x1)/2; while(fabs(x1-x0)>E) { printf("\n %d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f",count,x0,x1,x2,f(x0),f(x1
),f(x2)); if(f(x0)*f(x2)<0) { x1=x2; } else { x0=x2; } count++; x2=(x0+x1)/2; } printf("\nRoot is %f",x2); } else { clrscr(); printf("\nYour value is incorrect...\nPlease enter a new value then Press 'Y' key otherwise any key press to exit!...."); fflush(stdin); scanf("%c",&ch); if(ch=='y'||ch=='Y') { goto xyz; } else { exit(0); } } getch(); }
What are good resources for numerical methods programming for Java beginners?
ReplyDeletehttp://www.alpcentauri.info/nmusingjava.htm