fork download
  1. #include<iostream>
  2. #include<iomanip>
  3. #include<cmath>
  4. using namespace std;
  5. //siedel
  6. // Functions to calculate next iteration values
  7. inline double f1(double y, double z) { return (17 - y + 2 * z) / 20; }
  8. inline double f2(double x, double z) { return (-18 - 3 * x + z) / 20; }
  9. inline double f3(double x, double y) { return (25 - 2 * x + 3 * y) / 20; }
  10.  
  11. bool hasConverged(double e1, double e2, double e3, double tolerance) {
  12. return (e1 <= tolerance && e2 <= tolerance && e3 <= tolerance);
  13. }
  14.  
  15. int main() {
  16. double x = 0, y = 0, z = 0, newX, newY, newZ, tol;
  17. int step = 1;
  18.  
  19. cout << "Enter tolerable error: ";
  20. cin >> tol;
  21. cout << fixed << setprecision(6);
  22. cout << "\nIteration\tx\t\ty\t\tz" << endl;
  23.  
  24. do {
  25. newX = f1(y, z);
  26. newY = f2(newX, z);
  27. newZ = f3(newX, newY);
  28.  
  29. cout << step++ << "\t" << newX << "\t" << newY << "\t" << newZ << endl;
  30.  
  31. double e1 = fabs(newX - x);
  32. double e2 = fabs(newY - y);
  33. double e3 = fabs(newZ - z);
  34.  
  35. x = newX;
  36. y = newY;
  37. z = newZ;
  38.  
  39. if (hasConverged(e1, e2, e3, tol)) {
  40. break;
  41. }
  42. } while (true);
  43.  
  44. cout << "\nSolution: x = " << x << ", y = " << y << ", z = " << z << endl;
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5292KB
stdin
0.0001
stdout
Enter tolerable error: 
Iteration	x		y		z
1	0.850000	-1.027500	1.010875
2	1.002463	-0.999826	0.999780
3	0.999969	-1.000006	1.000002
4	1.000001	-1.000000	1.000000

Solution: x = 1.000001, y = -1.000000, z = 1.000000