fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. pair<double,double> horner(const vector<double>& a, double x){
  5. double n = a.size() - 1;
  6. double p = a[0];
  7. double dp = 0;
  8. for(int i = 1; i <= n; i++){
  9. dp = dp * x + p;
  10. p = p * x + a[i];
  11. }
  12. return {p, dp};
  13. }
  14.  
  15. int main(){
  16. int n;
  17. cin >> n;
  18. vector<double> a(n+1);
  19. for(int i = 0; i <= n; i++) cin >> a[i];
  20.  
  21. double x0;
  22. cin >> x0;
  23. double E = 1e-8;
  24.  
  25. cout << fixed << setprecision(8);
  26. cout << "Iter\t x\t\t f(x)\t\t f'(x)\t\t error\n";
  27.  
  28. for(int i = 1; i <= 100; i++){
  29. auto [fx, dfx] = horner(a, x0);
  30. if(dfx == 0){
  31. cout << "Derivative zero. Stopping iteration.\n";
  32. break;
  33. }
  34. double x1 = x0 - fx / dfx;
  35. cout << i << "\t" << x0 << "\t" << fx << "\t" << dfx << "\t" << fabs(x1 - x0) << "\n";
  36. if(fabs(x1 - x0) < E) {
  37. cout << "Root = " << x1 << "\n";
  38. break;
  39. }
  40. x0 = x1;
  41. }
  42. }
Success #stdin #stdout 0s 5268KB
stdin
2
1
stdout
Iter	 x		 f(x)		 f'(x)		 error
1	0.00000000	0.00000000	0.00000000	0.00000000
Root = 0.00000000