fork download
  1.  
  2. //Falsi
  3. #include<bits/stdc++.h>
  4.  
  5. using namespace std;
  6.  
  7. double f(double x){
  8.  
  9. return pow(x,3) - 4;
  10. }
  11. int main(){
  12. double x1 = 1.0;
  13. double x2 = 3.0;
  14. double x0;
  15. double f1=f(x1);
  16. double f2=f(x2);
  17. cout<<"Iteration\t"<<"x0\t\t"<<"x1\t\t"<<"x2\t\t"<<"f0\t\t"<<"f1\t\t"<<"f2\n";
  18. if (f1*f2>0){
  19. cout<<"Invalid! do not bracket any root in this interval."<<endl;
  20. return 1;
  21. }
  22. for(int i=0;i<3;i++){
  23. x0 = x1 - (f(x1)*(x2-x1)) / (f(x2)-f(x1));
  24. double f0 = f(x0);
  25. cout<<i+1<<"\t"<<x0<<"\t\t\t"<<x1<<"\t\t\t"<<x2<<"\t\t\t"<<f0<<"\t\t\t"<<f1<<"\t\t\t"<<f2<<"\n";
  26. if (f0==0){
  27. cout<<"X0 is the root of the equation "<<x0<<endl;
  28. break;
  29. }
  30. if(f1*f2<0){
  31. x2 = x0;
  32. f2 = f(x2);
  33. }
  34. else{
  35. x1 = x0;
  36. f1= f(x1);
  37. }
  38. cout<<fixed<<setprecision(5);
  39.  
  40. }
  41. cout<<"After 3 iteration approximate root is :"<<x0<<endl;
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5252KB
stdin
Standard input is empty
stdout
Iteration	x0		x1		x2		f0		f1		f2
1	1.23077			1			3			-2.13564			-3			23
2	1.80095			1.00000			1.23077			1.84122			-3.00000			-2.13564
3	1.53696			1.80095			1.23077			-0.36929			1.84122			-2.13564
After 3 iteration approximate root is :1.53696