您好我检查了很多其他问题,但似乎无法弄清楚为什么我的实施不会收敛。我一直得到"错误,没有收敛"我的程序的一部分,即使我进入root。
函数是y = x ^ 2 - 1
以下是代码:
// Newton sqaure root finder function
#include <iostream>
#include <cmath>
int main()
{
using namespace std;
// Enter an initial guess x
cout << "Enter an initial guess: ";
double x;
cin >> x;
// Define & initialize the error, tolerance and iteration variables
double tol = 1e-12;
cout << 1e-12;
double error = tol + 1;
int it = 0;
int max_it = 100;
// Define the x1 variable to hold the latest result (root approximation)
double x1;
// Start while loop with guess x to find the root
while (error > tol && it < max_it)
{
x1 = x + (x*x-1) / (2*x);
error = fabs(x1 - x);
x = x1;
it++;
cout << error << endl;
}
if (error <= tol)
{
cout << "The root is " << x << endl;
}
else
{
cout << "Error, no convergence" << endl;
}
cin.get();
cin.get();
return 0;
}
答案 0 :(得分:3)
公式
中有拼写错误x1 = x + (x*x-1) / (2*x);
应该是
x1 = x - (x*x-1) / (2*x);
您可以在此处看到:https://en.wikipedia.org/wiki/Methods_of_computing_square_roots