用牛顿法求方程的根x^2-e^x=0的C++程序代码
时间: 2024-09-23 08:02:34 浏览: 52
使用牛顿迭代法求解非线性方程 `f(x) = x^2 - e^x = 0` 的C++程序代码可以如下所示:
```cpp
#include <iostream>
#include <cmath>
double function(double x) {
return pow(x, 2) - exp(x);
}
double derivative(double x) {
return 2 * x - exp(x);
}
double newtonRaphson(double x0, double epsilon, int maxIterations) {
if (epsilon <= 0) {
std::cerr << "Error: Epsilon must be a positive value." << std::endl;
return 0;
}
int iteration = 0;
double nextX = x0;
while (iteration < maxIterations && abs(function(nextX)) > epsilon) {
nextX -= function(nextX) / derivative(nextX);
iteration++;
}
if (iteration == maxIterations) {
std::cout << "Warning: Maximum number of iterations reached (" << maxIterations << "). No solution found within the specified tolerance." << std::endl;
}
return nextX;
}
int main() {
const double initialGuess = 0; // 初始猜测值
const double tolerance = 1e-6; // 求解精度
const int maxIter = 100; // 最大迭代次数
double root = newtonRaphson(initialGuess, tolerance, maxIter);
if (root != 0) {
std::cout << "The root of the equation is approximately: " << root << std::endl;
}
return 0;
}
```
这个程序首先定义了函数 `function` 和其导数 `derivative`,然后实现了牛顿法 `newtonRaphson`,该方法接受初始猜测值、容差和最大迭代次数作为输入。如果找到满足条件的根,则返回结果;否则给出警告信息。
阅读全文