It is necessary to implement the Newton method for finding the root of the equation tan(7 * x) + x^2*sin(x) + 1 = 0 . Here is my code

 int main() { double x0; //Грубое приближение double eps; //Шаг(точность) double a, b; //Границы интервала double amendment; //Поправка к значению х0 double s; //Solution - решение double x1; // Начальная функция = tan(7 * x) + x*x*sin(x) + 1; - начальная функция // Производная от этой функции = (7 / (pow(cos(7*x), 2)) + 2 * x*sin(x) + x*x*cos(x)); setlocale(LC_ALL, "Russian"); cout << "Введите грубое приближение x0, EPS и нажмите Enter" << endl; cin >> x0 >> eps; cout << "Введите границы интервала [a;b]" << endl; cin >> a >> b; if (eps < 0) cout << "Ошибка! Шаг не может быть отрицательным числом!" << endl; if (x0 > b || x0 < a) cout << "Ошибка! Грубое приближения корня х0 должно входить в промежуток [a,b]!" << endl; do { amendment = ((-1)*tan(7 * x0) + x0*x0*sin(x0) + 1) / ((7 / (pow(cos(7 * x0), 2)) + 2 * x0*sin(x0) + x0*x0*cos(x0))); x1 = x0 + amendment; if (tan(7 * x1) + x1*x1*sin(x1) + 1 == 0) break; x0 = x1; } while ((tan(7 * x1) + x1*x1*sin(x1) + 1 != 0)); s = x1; cout << "Корень уравнения = " << s << endl; system("pause"); return 0; } 

But with my code it turns out an endless loop. What did I miss, how best to fix the problem?

-

Newton's algorithm:

  1. Find a rough approximation of the root X0 .
  2. Calculate the correction to the value of X0 : Dx = -f(X0)/f'(X0) .
  3. The new value of X1 = X0 + Dx .
  4. Check condition f(X1) = 0 .
  5. If you are not satisfied, go to step 2, but with x = х1 .
  • one
    it is likely that you will spin around zero to infinity, try not to check for equality to zero, but to match a certain epsolon while ((tan(7 * x1) + x1*x1*sin(x1) + 1 < 0.000000001)); - Yuriy Orlov
  • And in principle, to make an exact comparison of double or float variables is very rarely true, they almost always exist in memory with an error. - Yuriy Orlov
  • one
    Does it bother you that entered eps is not used anywhere in the program? - dzhioev

1 answer 1

  1. On the topic of eps everything is said, instead of the condition y != 0 you must use the condition |y| > eps |y| > eps .
  2. In the formula for amendent the minus sign should refer to the whole numerator, and not just to the tangent.
  3. Derivative calculated correctly.