fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. double f(double x){return x*x*x - 4;}
  4. int main(){
  5. double x1=1,x2=3,x0,f1,f2,f0,E=1e-8;
  6. f1=f(x1); f2=f(x2);
  7. cout<<"Iter\t x1\t\t x2\t\t x0\t\t f1\t\t f2\t\t f0\n";
  8. for(int i=1;i<=3;i++){
  9. x0=x1-(f1*(x2-x1))/(f2-f1); f0=f(x0);
  10. cout<<i<<"\t"<<x1<<"\t"<<x2<<"\t"<<x0<<"\t"<<f1<<"\t"<<f2<<"\t"<<f0<<"\n";
  11. if(f1*f0<0) x2=x0; else x1=x0;
  12. f1=f(x1); f2=f(x2);
  13. }
  14. }
Success #stdin #stdout 0.01s 5320KB
stdin
3
-6
stdout
Iter	 x1		 x2		 x0		 f1		 f2		 f0
1	1	3	1.23077	-3	23	-2.13564
2	1.23077	3	1.38109	-2.13564	23	-1.36569
3	1.38109	3	1.47183	-1.36569	23	-0.811596