Guest User

Untitled

a guest
May 22nd, 2012
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. double equation (double x)
  7. {
  8. return x*x*x + x * x - 4*x - 4;
  9. }
  10.  
  11. double derivative1 (double x)
  12. {
  13. return 3*x*x + 2*x - 4;
  14. }
  15.  
  16. double derivative2 (double x)
  17. {
  18. return 6*x + 2;
  19. }
  20.  
  21. namespace methods
  22. {
  23. double chord (double a, double b, double accuracy=0.001)
  24. {
  25. double result;
  26.  
  27. if (fabs(equation(a)) < accuracy)
  28. {
  29. return a;
  30. }
  31.  
  32. if (fabs(equation(b)) < accuracy)
  33. {
  34. return b;
  35. }
  36.  
  37. double c = a - (equation(a)*(b-a)/(equation(b)-equation(a)));
  38.  
  39. if (fabs(equation(c)+equation(a)) < fabs(equation(c))+fabs(equation(a)))
  40. {
  41. result = chord(a, c, accuracy);
  42. }
  43. else
  44. {
  45. result = chord(c, b, accuracy);
  46. }
  47.  
  48. return result;
  49. }
  50.  
  51. double newton (double a, double b, double accuracy=0.001)
  52. {
  53. double c = (equation(a) * derivative2(a) > 0) ? a : b;
  54.  
  55. while (fabs(equation(c)) > accuracy)
  56. {
  57. c = c - equation(c) / derivative1(c);
  58. }
  59.  
  60. return c;
  61. }
  62.  
  63. double modifiedNewton (double a, double b, double accuracy=0.001)
  64. {
  65. double c = (equation(a) * derivative2(a) > 0) ? a : b;
  66. double d = derivative1(c);
  67.  
  68. while (fabs(equation(c)) > accuracy)
  69. {
  70. c = c - equation(c) / d;
  71. }
  72.  
  73. return c;
  74. }
  75.  
  76. double combined (double a, double b, double accuracy=0.001)
  77. {
  78. if (equation(a) < equation(b)) swap(a,b);
  79.  
  80. while (fabs(a - b) > accuracy)
  81. {
  82. a = a - equation(a) / (derivative1(a) - equation(a)) * (b - a);
  83. b = b - equation(b) / derivative1(b);
  84. }
  85.  
  86. return (a + b) / 2;
  87. }
  88. }
  89.  
  90.  
  91. int main ()
  92. {
  93. double a;
  94. double b;
  95. double accuracy;
  96.  
  97. cout << "Введите интервал для поиска корня (a b): ";
  98. cin >> a >> b;
  99.  
  100. if (a > b) swap(a, b);
  101.  
  102. cout << "Введите точность: ";
  103. cin >> accuracy;
  104.  
  105. cout << endl;
  106.  
  107. cout << "Результаты:\n";
  108. cout << "Метод хорд: " << methods::chord(a, b, accuracy) << endl;
  109. cout << "Метод касательных: " << methods::newton(a, b, accuracy) << endl;
  110. cout << "Модифицированный метод Ньютона: " << methods::modifiedNewton(a, b, accuracy) << endl;
  111. cout << "Комбинированный метод: " << methods::combined(a, b, accuracy) << endl;
  112.  
  113. return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment