C++ C+中的牛顿方法+;

C++ C+中的牛顿方法+;,c++,newtons-method,C++,Newtons Method,您好,我已经检查了许多其他问题,但似乎不明白为什么我的实现不会收敛。即使在我输入根时,我也会不断得到程序中的“错误,不收敛”部分 函数是y=x^2-1 代码如下: // Newton sqaure root finder function #include <iostream> #include <cmath> int main() { using namespace std; // Enter an initial guess x cout << "E

您好,我已经检查了许多其他问题,但似乎不明白为什么我的实现不会收敛。即使在我输入根时,我也会不断得到程序中的“错误,不收敛”部分

函数是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;
}
//Newton sqaure根查找器函数
#包括
#包括
int main()
{
使用名称空间std;
//输入初始猜测x
cout>x;
//定义并初始化错误、公差和迭代变量
双tol=1e-12;
cout-tol&it你的公式有错吗

x1 = x + (x*x-1) / (2*x);
应该是

x1 = x - (x*x-1) / (2*x);

您可以在这里看到:

公式中有一个输入错误

x1 = x + (x*x-1) / (2*x);
应该是

x1 = x - (x*x-1) / (2*x);

您可以在此处看到:

这是一个使用调试器的完美程序。您可能在撰写本文的时间内找到了答案。很抱歉,我不知道如何使用调试器。您可以将网站或其他内容链接到我的网站上,说明如何使用调试器吗?谢谢!这很大程度上取决于您编写的平台r代码/您使用的编译器。我使用的是visual basic studio 13(windows 10)@DoubleOseven,它只是Visual Studio,而不是Basic。这是一个使用调试器的完美程序。你可能会在撰写本文的时间内找到答案。很抱歉,我不知道如何使用调试器。你能给我链接一个网站或什么东西,上面写着如何完成调试器吗?谢谢!这很大程度上取决于您在什么平台上编写代码/使用什么编译器。我使用的是visual basic studio 13(windows 10)@DoubleOseven,它只是visual studio,而不是basic。