C++求解牛顿迭代法的Polynomial.h 头文件
时间: 2023-12-21 21:06:06 浏览: 114
利用牛顿迭代程序求解的C++程序
下面是一个简单的Polynomial类的头文件,其中包含了牛顿迭代法的实现:
```c++
#include <vector>
class Polynomial {
public:
Polynomial(std::vector<double> coeffs);
double operator()(double x) const;
Polynomial derivative() const;
double newton(double x0, double eps, int max_iters) const;
private:
std::vector<double> coeffs_;
};
Polynomial::Polynomial(std::vector<double> coeffs) : coeffs_(std::move(coeffs)) {}
double Polynomial::operator()(double x) const {
double result = 0;
for (int i = coeffs_.size() - 1; i >= 0; --i) {
result = result * x + coeffs_[i];
}
return result;
}
Polynomial Polynomial::derivative() const {
std::vector<double> der_coeffs;
for (int i = 1; i < coeffs_.size(); ++i) {
der_coeffs.push_back(i * coeffs_[i]);
}
return Polynomial(der_coeffs);
}
double Polynomial::newton(double x0, double eps, int max_iters) const {
double x = x0;
for (int i = 0; i < max_iters; ++i) {
double fx = (*this)(x);
double fx_deriv = derivative()(x);
if (std::abs(fx_deriv) < eps) {
throw std::runtime_error("Newton iteration failed: zero derivative");
}
double x_new = x - fx / fx_deriv;
if (std::abs(x_new - x) < eps) {
return x_new;
}
x = x_new;
}
throw std::runtime_error("Newton iteration failed: maximum iterations exceeded");
}
```
在这个头文件中,`Polynomial`类表示一个多项式,使用一个`std::vector<double>`来存储多项式系数。`operator()`方法用于计算多项式在给定点的值,`derivative()`方法用于计算多项式的导函数,`newton()`方法用于使用牛顿迭代法求解多项式的根。注意,在`newton()`方法中,我们使用`derivative()`方法来计算导函数。
阅读全文