Advertisement
Sourav_CSE

Bisection.c

Mar 22nd, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. // Bisection method with maximum iteration
  2. // Lab Class No 1
  3. #include<stdio.h>
  4.  
  5. double my_function(double x) //returns the value of x
  6. {
  7. double fx=(x*x)-x-1;
  8. return fx;
  9. }
  10.  
  11. double bisection(double a, double b, double tolerance, int max_iter)
  12. {
  13. double prev_root,x,ans;
  14. int i;
  15. for(i=1;i<max_iter;i++)
  16. {
  17. x=(a+b)/2.00;
  18. ans=my_function(x);
  19. if(my_function(a)<0 && ans<0) //if both of these are negative
  20. //then update the negative one
  21. {
  22. a=x;
  23. }
  24. else
  25. b=x;
  26. }
  27. return x;
  28. }
  29. int main()
  30. {
  31. // f(x0=x^2-x-1;
  32. float a,b,x,tolerance,root;
  33. int max_iter;
  34. // Enter the range [a,b], tolerance and maximum iteration
  35. scanf("%lf %lf %lf %d", &a, &b, &tolerance, &max_iter);
  36.  
  37. if(my_function(a)*my_function(b)>0) // Check the range
  38. printf("Invalid Range\n");
  39. else
  40. {
  41. root=bisection(a,b,tolerance,max_iter);
  42. printf("%lf\n",root);
  43. }
  44. }
  45.  
  46. /*
  47. Input:
  48. 2 3
  49. 0.001
  50. 100
  51. Output:
  52. 2.125000
  53. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement