Advertisement
Guest User

Untitled

a guest
Oct 28th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <cmath>
  4. using namespace std;
  5. double f(double x)
  6. {
  7. return x*x - 3;
  8. }
  9. double derivative(double x)
  10. {
  11. return 2*x;
  12. }
  13. double sign(double f)
  14. {
  15. return f >= 0;
  16. }
  17.  
  18. double newton(double a, double b, double eps)
  19. {
  20. double x = (a + b) / 2;
  21. double x1 = 0;
  22. for(; abs(x-x1) > eps;)
  23. {
  24. x1 = x;
  25. if (derivative(x) == 0 && f(x) != 0)
  26. {
  27. cout << "Newton Method can not be used!";
  28. return 0;
  29. }
  30. if (derivative(x) == 0 && f(x) == 0)
  31. {
  32. cout << "Newton Method = 0";
  33. return 0;
  34. }
  35. x = x - f(x) / derivative(x);
  36. }
  37. return x;
  38. }
  39.  
  40. void iter(double a, double b, double eps)
  41. {
  42. double x = (a + b) / 2;
  43. for (int i = 0;; ++i)
  44. {
  45. double x0 = x + f(x);
  46. if (x == x0)
  47. {
  48. cout << "Iteration method = " << x << endl;
  49. return;
  50. }
  51. if (i == 10) {
  52. if (abs(x0-x) < eps)
  53. {
  54. cout << "Iteration method priblizitelno = " << (x0 + x) / 2 << endl;
  55. return;
  56. }
  57. else
  58. {
  59. cout << "Iteration method ne imeet resheniya" << endl;
  60. return;
  61. }
  62. }
  63. x = x0;
  64. }
  65. }
  66.  
  67. double bisec(double a, double b, double eps)
  68. {
  69. double res = (a + b)/2;
  70. for (; abs(b-a) > eps; )
  71. {
  72. if (sign(f(a)) == sign(f(res)))
  73. {
  74. a = res;
  75. }
  76. else
  77. {
  78. b = res;
  79. }
  80. if (f(res) == 0)
  81. {
  82. return res;
  83. }
  84. res = (a + b) / 2;
  85. }
  86. return res;
  87. }
  88.  
  89. int main(int argc, char* argv[])
  90. {
  91. double a, b, eps;
  92. cout << "Enter a, b and eps" << endl;
  93. cin >> a >> b >> eps;
  94. cout << "Bisection method result: " << bisec(a, b, eps) << endl;
  95. cout << "Iterazii method result: " << iter(a, b, eps) << endl;
  96. cout << "Newtona method result: " << newton(a, b, eps) << endl;
  97. }
  98. return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement