// wangdiedang is a good guy! =v=
#include<iostream>
#include<vector>
#include<cmath>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
double z(double x) {
return exp(5 * x) - sin(x) + pow(x, 3) - 20;
}
double z1(double x) {
return 5 * exp(5 * x) - cos(x) + 3 * pow(x, 2);
}
void newton(double x0, double M, double eps) {
int k = 1; double c1, c2,dt,x = x0,x1;
while (k < M) {
c1 = z(x); // xk的函数值
c2 = z1(x); // xk的导数值
if (c1 * c2 == 0) break;
else x1 = x - c1 / c2;
if (fabs(x1) < 1) dt = fabs(x1 - x);
else dt = fabs(x1 - x) / fabs(x1);
if (dt < eps) break; // 差值如果小于所要求的精度 break;
x = x1;
k++;
}
cout << "x" + to_string(k) + ": " << setiosflags(ios::fixed) << setprecision(8) << x;
}
int main() {
double x0, M, eps;
cin >> x0 >> M >> eps; // x初值和最大迭代次数和精度
newton(x0, M, eps);
return 0;
}
数值分析试验五 牛顿迭代 c++代码
最新推荐文章于 2024-07-24 11:32:27 发布