Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Bisection method with maximum iteration
- // Lab Class No 1
- #include<stdio.h>
- double my_function(double x) //returns the value of x
- {
- double fx=(x*x)-x-1;
- return fx;
- }
- double bisection(double a, double b, double tolerance, int max_iter)
- {
- double prev_root,x,ans;
- int i;
- for(i=1;i<max_iter;i++)
- {
- x=(a+b)/2.00;
- ans=my_function(x);
- if(my_function(a)<0 && ans<0) //if both of these are negative
- //then update the negative one
- {
- a=x;
- }
- else
- b=x;
- }
- return x;
- }
- int main()
- {
- // f(x0=x^2-x-1;
- float a,b,x,tolerance,root;
- int max_iter;
- // Enter the range [a,b], tolerance and maximum iteration
- scanf("%lf %lf %lf %d", &a, &b, &tolerance, &max_iter);
- if(my_function(a)*my_function(b)>0) // Check the range
- printf("Invalid Range\n");
- else
- {
- root=bisection(a,b,tolerance,max_iter);
- printf("%lf\n",root);
- }
- }
- /*
- Input:
- 2 3
- 0.001
- 100
- Output:
- 2.125000
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement