c++中的牛顿方法

Newtons method in C++

本文关键字:方法 c++      更新时间:2023-10-16

嗨,我已经检查了许多其他问题,但似乎无法弄清楚为什么我的实现不会收敛。我一直得到"错误,没有收敛"的部分,我的程序,甚至当我进入根。

函数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;
}

你的公式中有一个打字错误

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

应该是

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

你可以在这里看到:https://en.wikipedia.org/wiki/Methods_of_computing_square_roots