fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <iomanip>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. double f(double x) {
  9. return pow(x, 3) - x - 3;
  10. }
  11.  
  12.  
  13. double f_prime(double x) {
  14. return 3 * pow(x, 2) - 1;
  15. }
  16.  
  17. int main() {
  18. double x0 = 3.0;
  19. double x1;
  20. double tolerance = 1e-6;
  21. int max_iterations = 100;
  22. int iteration = 1;
  23.  
  24. cout << fixed << setprecision(6);
  25. cout << "**************************************" << endl;
  26. cout << "ITERATION\tX\t\tf(X)\t\tf'(X)" << endl;
  27. cout << "**************************************" << endl;
  28.  
  29. while (iteration <= max_iterations) {
  30. double fx = f(x0);
  31. double fpx = f_prime(x0);
  32.  
  33. if (fpx == 0.0) {
  34. cout << "Derivative is zero. No solution found." << endl;
  35. return -1;
  36. }
  37.  
  38. x1 = x0 - fx / fpx;
  39.  
  40. cout << iteration << "\t\t" << x0 << "\t" << fx << "\t" << fpx << endl;
  41.  
  42. if (fabs((x1 - x0) / x1) < tolerance) {
  43. cout << "**************************************" << endl;
  44. cout << "THE ROOT OF EQUATION IS " << x1 << endl;
  45. break;
  46. }
  47.  
  48. x0 = x1;
  49. iteration++;
  50. }
  51.  
  52. if (iteration > max_iterations) {
  53. cout << "Did not converge to a solution within the maximum number of iterations." << endl;
  54. }
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0.01s 5324KB
stdin
x^0::-3
x^1::-1
x^2::0
x^3::1
stdout
**************************************
ITERATION	X		f(X)		f'(X)
**************************************
1		3.000000	21.000000	26.000000
2		2.192308	5.344390	13.418639
3		1.794027	0.980105	8.655594
4		1.680793	0.067556	7.475195
5		1.671756	0.000411	7.384300
6		1.671700	0.000000	7.383742
**************************************
THE ROOT OF EQUATION IS 1.671700