fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. pair<double,double> horner(vector<double>a,double x){
  4. double p=a[0],dp=0;
  5. for(int i=1;i<a.size();i++){dp=dp*x+p; p=p*x+a[i];}
  6. return {p,dp};
  7. }
  8. int main(){
  9. int n;cin>>n;vector<double>a(n+1);
  10. for(int i=0;i<=n;i++)cin>>a[i];
  11. double x0;cin>>x0;double E=1e-8;
  12. cout<<"Iter\t x\t\t f(x)\t\t f'(x)\t\t error\n";
  13. for(int i=1;i<=100;i++){
  14. auto [fx,dfx]=horner(a,x0);
  15. double x1=x0-fx/dfx;
  16. cout<<i<<"\t"<<x0<<"\t"<<fx<<"\t"<<dfx<<"\t"<<fabs(x1-x0)<<"\n";
  17. if(fabs((x1-x0)/x1)<E){cout<<"Root="<<x1;break;}
  18. x0=x1;
  19. }
  20. }
Success #stdin #stdout 0s 5300KB
stdin
2
-1
stdout
Iter	 x		 f(x)		 f'(x)		 error
1	4.94066e-324	0	-9.88131e-324	0
Root=4.94066e-324