C++中的牛顿法
Newtons method in C++
您好,我已经检查了许多其他问题,但似乎无法弄清楚为什么我的实现不会收敛。即使进入根目录,我也一直在获取程序的 "Error, no convergence" 部分。
函数是 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
您好,我已经检查了许多其他问题,但似乎无法弄清楚为什么我的实现不会收敛。即使进入根目录,我也一直在获取程序的 "Error, no convergence" 部分。
函数是 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