fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. double functionVal(double x) {
  6. return x * x * x - 4.0;
  7. }
  8.  
  9. double derivativeVal(double x) {
  10. return 3.0 * x * x;
  11. }
  12.  
  13. int main() {
  14. double current, next, f_val, f_deriv, tolerance = 0.0001, approxRoot;
  15. int iteration = 0;
  16.  
  17. cout << "Enter initial guess: ";
  18. cin >> current;
  19.  
  20.  
  21. f_val = functionVal(current);
  22. f_deriv = derivativeVal(current);
  23. next = current - (f_val / f_deriv);
  24.  
  25. cout << "Iter\tCurrent\t\tf(x)\t\tf'(x)\t\tNext\n";
  26. cout << iteration << "\t" << fixed << setprecision(8)
  27. << current << "\t" << f_val << "\t" << f_deriv << "\t" << next << endl;
  28.  
  29. while (true) {
  30. f_val = functionVal(current);
  31. f_deriv = derivativeVal(current);
  32.  
  33. if (f_deriv == 0) {
  34. cout << "Derivative is zero. Cannot proceed." << endl;
  35. return -1;
  36. }
  37.  
  38. next = current - (f_val / f_deriv);
  39. iteration++;
  40.  
  41. cout << iteration << "\t" << fixed << setprecision(8)
  42. << current << "\t" << f_val << "\t" << f_deriv << "\t" << next << endl;
  43.  
  44. if (fabs((next - current) / next) < tolerance || iteration > 8)
  45. break;
  46.  
  47. approxRoot = next;
  48. current = next;
  49. }
  50.  
  51. cout << fixed << setprecision(8);
  52. cout << "Approximate root = " << approxRoot << endl;
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5320KB
stdin
-1
stdout
Enter initial guess: Iter	Current		f(x)		f'(x)		Next
0	-1.00000000	-5.00000000	3.00000000	0.66666667
1	-1.00000000	-5.00000000	3.00000000	0.66666667
2	0.66666667	-3.70370370	1.33333333	3.44444444
3	3.44444444	36.86556927	35.59259259	2.40867923
4	2.40867923	9.97452013	17.40520691	1.83560244
5	1.83560244	2.18494552	10.10830895	1.61944902
6	1.61944902	0.24719152	7.86784541	1.58803108
7	1.58803108	0.00476460	7.56552813	1.58740130
8	1.58740130	0.00000189	7.55952868	1.58740105
Approximate root = 1.58740130