fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. double f(double x) {
  5. return 2 * x * x * x + 3 * x - 1;
  6. }
  7.  
  8. double df(double x) {
  9. return 6 * x * x + 3;
  10. }
  11.  
  12. int main() {
  13. double x0, x1, E = 1e-8;
  14. int i = 0;
  15. cout << "Enter initial guess: ";
  16. cin >> x0;
  17. cout << "Iter\t x0\t\t f(x0)\t\t f'(x0)\t\t x1\n";
  18. do {
  19. double f0 = f(x0);
  20. double df0 = df(x0);
  21. if (df0 == 0) {
  22. cout << "Derivative is zero. Cannot continue.\n";
  23. return 0;
  24. }
  25. x1 = x0 - f0 / df0;
  26. cout << ++i << "\t" << x0 << "\t" << f0 << "\t" << df0 << "\t" << x1 << "\n";
  27. if (fabs(x1 - x0) < E)
  28. break;
  29. x0 = x1;
  30. } while (true);
  31. cout << "\nApproximate root = " << x1 << endl;
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Enter initial guess: Iter	 x0		 f(x0)		 f'(x0)		 x1
1	4.65861e-310	-1	3	0.333333
2	0.333333	0.0740741	3.66667	0.313131
3	0.313131	0.000799753	3.58831	0.312908
4	0.312908	9.33056e-08	3.58747	0.312908
5	0.312908	1.33227e-15	3.58747	0.312908

Approximate root = 0.312908