Advertisement
Sourav_CSE

Bisection.cpp

Mar 13th, 2020
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. // Lab Class No 1
  2. // Bisection Method using max iteration
  3. // Shachin shil
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6. double my_fun(double x)
  7. {
  8. double fx=(x*x)-x-1;
  9. return fx;
  10. }
  11. double fun(double a,double b,double tolerance,int max_iter)
  12. {
  13. double prev,ans,x;
  14.  
  15. for(int i=1;i<max_iter;i++)
  16. {
  17. x=(a+b)/2.00;
  18. ans=my_fun(x);
  19. if(ans<0 && my_fun(a)<0)
  20. {
  21. a=x;
  22. }
  23. else
  24. b=x;
  25. }
  26. return x;
  27.  
  28. }
  29. int main()
  30. {
  31. float a,b,x,tolerance,root;
  32. int max_iter;
  33. cin>>a>>b>>tolerance>>max_iter;
  34. if(my_fun(a)*my_fun(b)>0)
  35. {
  36. cout<<"Invalid"<< endl;
  37. }
  38. else
  39. {
  40. root=fun(a,b,tolerance,max_iter);
  41. cout<<root<<endl;
  42. }
  43.  
  44. return 0;
  45. }
  46.  
  47. /*
  48. Input :
  49. 1
  50. 2
  51. .001
  52. 100
  53. Output :
  54. 1.61803
  55. /*
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement