fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. double f(double x) {
  8. return x*x*x - 4;
  9. }
  10.  
  11. int main() {
  12. double x1, x2, x0, f1, f2, f0;
  13. double true_root = cbrt(4);
  14.  
  15. x1 = 1.0;
  16. x2 = 3.0;
  17.  
  18. f1 = f(x1);
  19. f2 = f(x2);
  20.  
  21. if (f1 * f2 > 0) {
  22. cout << "Initial values do not bracket a root!" << endl;
  23. return 1;
  24. }
  25.  
  26. cout << fixed << setprecision(6);
  27. cout << "False Position Method for f(x) = x³ - 4" << endl;
  28. cout << "True root: " << true_root << endl << endl;
  29.  
  30. cout << "Iteration\tx1\t\tx2\t\tx0\t\tf(x1)\t\tf(x2)\t\tf(x0)\t\tError\t\t% Error" << endl;
  31. cout << "--------------------------------------------------------------------------------------------------------" << endl;
  32.  
  33. for (int iteration = 1; iteration <= 3; iteration++) {
  34.  
  35. x0 = x1 - (f1 * (x2 - x1)) / (f2 - f1);
  36. f0 = f(x0);
  37.  
  38. double error = fabs(x0 - true_root);
  39. double percent_error = (error / true_root) * 100;
  40.  
  41. cout << iteration << "\t\t" << x1 << "\t" << x2 << "\t" << x0
  42. << "\t" << f1 << "\t" << f2 << "\t" << f0
  43. << "\t" << error << "\t" << percent_error << endl;
  44.  
  45. if (f1 * f0 < 0) {
  46. x2 = x0;
  47. f2 = f0;
  48. } else {
  49. x1 = x0;
  50. f1 = f0;
  51. }
  52. }
  53.  
  54.  
  55. x0 = x1 - (f1 * (x2 - x1)) / (f2 - f1);
  56. f0 = f(x0);
  57. double error = fabs(x0 - true_root);
  58. double percent_error = (error / true_root) * 100;
  59.  
  60. cout << "\nAfter 3 iterations:" << endl;
  61. cout << "x3 = " << x0 << endl;
  62. cout << "f(x3) = " << f0 << endl;
  63. cout << "Error = " << error << endl;
  64. cout << "Percentage Error = " << percent_error << "%" << endl;
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
False Position Method for f(x) = x³ - 4
True root: 1.587401

Iteration	x1		x2		x0		f(x1)		f(x2)		f(x0)		Error		% Error
--------------------------------------------------------------------------------------------------------
1		1.000000	3.000000	1.230769	-3.000000	23.000000	-2.135640	0.356632	22.466397
2		1.230769	3.000000	1.381091	-2.135640	23.000000	-1.365689	0.206310	12.996706
3		1.381091	3.000000	1.471831	-1.365689	23.000000	-0.811596	0.115571	7.280488

After 3 iterations:
x3 = 1.523917
f(x3) = -0.460974
Error = 0.063484
Percentage Error = 3.999263%