C++ 高斯牛顿法代码示例:求解方程根
#include
using namespace std;
double f(double x) { return cos(x) - x; }
double df(double x) { return -sin(x) - 1; }
double d2f(double x) { return -cos(x); }
double newton(double x0) { double x = x0; double epsilon = 0.00001; int max_iterations = 100;
for (int i = 0; i < max_iterations; i++) {
double f_x = f(x);
double df_x = df(x);
double d2f_x = d2f(x);
if (abs(f_x) < epsilon) {
cout << "Converged after " << i << " iterations." << endl;
return x;
}
x = x - f_x / df_x;
if (abs(f_x / df_x) < epsilon) {
cout << "Converged after " << i << " iterations." << endl;
return x;
}
if (abs(d2f_x / df_x) > epsilon) {
cout << "Diverged after " << i << " iterations." << endl;
return NAN; // Not a number
}
}
cout << "Reached maximum number of iterations without converging." << endl;
return NAN;
}
int main() { double x0 = 1.0; // Initial guess double root = newton(x0); cout << "Root: " << root << endl; return 0; }
原文地址: https://www.cveoy.top/t/topic/oP0q 著作权归作者所有。请勿转载和采集!