fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define EPSILON 1e-5 // Adjusted to match the slide requirement
  5. #define MAX_ITER 100
  6.  
  7. double f1(double x, double y) { return x * x + y * y - 4; }
  8. double f2(double x, double y) { return pow(x, 4) + x - y * y + 1; }
  9.  
  10. double df1_dx(double x, double y) { return 2 * x; }
  11. double df1_dy(double x, double y) { return 2 * y; }
  12. double df2_dx(double x, double y) { return 4 * x * x * x + 1; }
  13. double df2_dy(double x, double y) { return -2 * y; }
  14.  
  15. void solve(double x0, double y0) {
  16. double x = x0, y = y0;
  17. int iter = 0;
  18.  
  19. printf("\n--- Starting Guess: x=%.2f, y=%.2f ---\n", x0, y0);
  20. printf("Iter\tX\t\tY\n");
  21.  
  22. while (iter <= MAX_ITER) {
  23. double F1 = f1(x, y);
  24. double F2 = f2(x, y);
  25.  
  26. // Print current iteration values
  27. printf("%d\t%.10f\t%.10f\n", iter, x, y);
  28.  
  29. // Check convergence based on slides
  30. if (fabs(F1) < EPSILON && fabs(F2) < EPSILON) {
  31. printf("Converged to solution.\n");
  32. return;
  33. }
  34.  
  35. double J11 = df1_dx(x, y);
  36. double J12 = df1_dy(x, y);
  37. double J21 = df2_dx(x, y);
  38. double J22 = df2_dy(x, y);
  39.  
  40. double det = J11 * J22 - J12 * J21;
  41. if (fabs(det) < 1e-12) {
  42. printf("Jacobian determinant too small. Method fails.\n");
  43. return;
  44. }
  45.  
  46. x += (-F1 * J22 + F2 * J12) / det;
  47. y += (-J11 * F2 + J21 * F1) / det;
  48. iter++;
  49. }
  50. printf("Did not converge.\n");
  51. }
  52.  
  53. int main() {
  54. // Define 3 sets of initial values as required
  55. double initial_x[] = {1.0, -1.5, 0.5};
  56. double initial_y[] = {1.0, 1.0, -1.5};
  57.  
  58. for (int i = 0; i < 3; i++) {
  59. solve(initial_x[i], initial_y[i]);
  60. }
  61.  
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
--- Starting Guess: x=1.00, y=1.00 ---
Iter	X		Y
0	1.0000000000	1.0000000000
1	1.0000000000	2.0000000000
2	1.0000000000	1.7500000000
3	1.0000000000	1.7321428571
4	1.0000000000	1.7320508100
Converged to solution.

--- Starting Guess: x=-1.50, y=1.00 ---
Iter	X		Y
0	-1.5000000000	1.0000000000
1	-1.3185483871	1.6471774194
2	-1.2775878160	1.5428333742
3	-1.2756861606	1.5403358963
4	-1.2756822037	1.5403359748
Converged to solution.

--- Starting Guess: x=0.50, y=-1.50 ---
Iter	X		Y
0	0.5000000000	-1.5000000000
1	1.3750000000	-1.7083333333
2	1.1035857261	-1.6900001066
3	1.0098267771	-1.7293315421
4	1.0000957562	-1.7320249495
5	1.0000000092	-1.7320508051
Converged to solution.