Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- using namespace std;
- double equation (double x)
- {
- return x*x*x + x * x - 4*x - 4;
- }
- double derivative1 (double x)
- {
- return 3*x*x + 2*x - 4;
- }
- double derivative2 (double x)
- {
- return 6*x + 2;
- }
- namespace methods
- {
- double chord (double a, double b, double accuracy=0.001)
- {
- double result;
- if (fabs(equation(a)) < accuracy)
- {
- return a;
- }
- if (fabs(equation(b)) < accuracy)
- {
- return b;
- }
- double c = a - (equation(a)*(b-a)/(equation(b)-equation(a)));
- if (fabs(equation(c)+equation(a)) < fabs(equation(c))+fabs(equation(a)))
- {
- result = chord(a, c, accuracy);
- }
- else
- {
- result = chord(c, b, accuracy);
- }
- return result;
- }
- double newton (double a, double b, double accuracy=0.001)
- {
- double c = (equation(a) * derivative2(a) > 0) ? a : b;
- while (fabs(equation(c)) > accuracy)
- {
- c = c - equation(c) / derivative1(c);
- }
- return c;
- }
- double modifiedNewton (double a, double b, double accuracy=0.001)
- {
- double c = (equation(a) * derivative2(a) > 0) ? a : b;
- double d = derivative1(c);
- while (fabs(equation(c)) > accuracy)
- {
- c = c - equation(c) / d;
- }
- return c;
- }
- double combined (double a, double b, double accuracy=0.001)
- {
- if (equation(a) < equation(b)) swap(a,b);
- while (fabs(a - b) > accuracy)
- {
- a = a - equation(a) / (derivative1(a) - equation(a)) * (b - a);
- b = b - equation(b) / derivative1(b);
- }
- return (a + b) / 2;
- }
- }
- int main ()
- {
- double a;
- double b;
- double accuracy;
- cout << "Введите интервал для поиска корня (a b): ";
- cin >> a >> b;
- if (a > b) swap(a, b);
- cout << "Введите точность: ";
- cin >> accuracy;
- cout << endl;
- cout << "Результаты:\n";
- cout << "Метод хорд: " << methods::chord(a, b, accuracy) << endl;
- cout << "Метод касательных: " << methods::newton(a, b, accuracy) << endl;
- cout << "Модифицированный метод Ньютона: " << methods::modifiedNewton(a, b, accuracy) << endl;
- cout << "Комбинированный метод: " << methods::combined(a, b, accuracy) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment