fork download
  1. //Newton
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. double f(double x) {
  5. return x*x*x - 2*x - 5;
  6. }
  7.  
  8.  
  9. double f_derivative(double x) {
  10. return 3*x*x - 2;
  11. }
  12.  
  13. int main() {
  14. double x0, x1, E;
  15. int iteration = 0;
  16.  
  17. cout << "Enter initial guess (x0): ";
  18. cin >> x0;
  19. cout << "Enter tolerance (E): ";
  20. cin >> E;
  21. cout<<"Iteration\t\tX1\t\t\tFX1\t\t\tF'X1"<<endl;
  22. do {
  23. double f0 = f(x0);
  24. double fprime = f_derivative(x0);
  25.  
  26. if (fprime == 0) {
  27. cout << "Mathematical Error! Derivative is zero.\n";
  28. return 0;
  29. }
  30.  
  31. x1 = x0 - (f0 / fprime);
  32. double f1=f(x1);
  33. double f_prime=f_derivative(x1);
  34. iteration++;
  35.  
  36. cout << iteration <<"\t\t"<< x1<<"\t\t\t"<<f1<<"\t\t\t"<<f_prime << endl;
  37. cout<<fixed<<setprecision(5);
  38. if (fabs((x1 - x0) / x1) < E)
  39. break;
  40.  
  41. x0 = x1;
  42.  
  43.  
  44. } while (true);
  45.  
  46. cout << "\nThe root is approximately: " << x1 << endl;
  47. cout << "Total iterations: " << iteration << endl;
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0.01s 5316KB
stdin
3
0.0001
stdout
Enter initial guess (x0): Enter tolerance (E): Iteration		X1			FX1			F'X1
1		2.36			3.42426			14.7088
2		2.12720			0.37110			11.57490
3		2.09514			0.00653			11.16879
4		2.09455			0.00000			11.16144
5		2.09455			0.00000			11.16144

The root is approximately: 2.09455
Total iterations: 5