fork(2) download
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdlib.h>
  4.  
  5. #define EPSILON 1e-6 // Convergence tolerance
  6. #define MAX_ITER 100 // Maximum iterations
  7.  
  8. // Define the nonlinear equations
  9. double f1(double x, double y) {
  10. return x * x + y * y - 4;
  11. }
  12.  
  13. double f2(double x, double y) {
  14. return x * x * x * x + x - y*y + 1; // Hyperbola: xy = 1
  15. }
  16.  
  17. // Partial derivatives for Jacobian matrix
  18. double df1_dx(double x, double y) { return 2 * x; }
  19. double df1_dy(double x, double y) { return 2 * y; }
  20. double df2_dx(double x, double y) { return 4 * x * x*x + 1; }
  21. double df2_dy(double x, double y) { return -2* y; }
  22.  
  23. int main() {
  24. double x = 1, y = 3; // Initial guess
  25. int iter = 0;
  26.  
  27. printf("Initial guess: x = %.6f, y = %.6f\n", x, y);
  28.  
  29. while (iter < MAX_ITER) {
  30. // Function values
  31. double F1 = f1(x, y);
  32. double F2 = f2(x, y);
  33.  
  34. // Check convergence
  35. if (fabs(F1) < EPSILON && fabs(F2) < EPSILON) {
  36. printf("Converged after %d iterations.\n", iter);
  37. printf("Solution: x = %.6f, y = %.6f\n", x, y);
  38. return 0;
  39. }
  40.  
  41. // Jacobian matrix
  42. double J11 = df1_dx(x, y);
  43. double J12 = df1_dy(x, y);
  44. double J21 = df2_dx(x, y);
  45. double J22 = df2_dy(x, y);
  46.  
  47. // Determinant of Jacobian
  48. double det = J11 * J22 - J12 * J21;
  49. if (fabs(det) < 1e-12) {
  50. printf("Jacobian determinant too small. Method fails.\n");
  51. return 1;
  52. }
  53.  
  54. // Inverse Jacobian * F
  55. double dx = (-F1 * J22 + F2 * J12) / det;
  56. double dy = (-J11 * F2 + J21 * F1) / det;
  57.  
  58. // Update variables
  59. x += dx;
  60. y += dy;
  61.  
  62. iter++;
  63. }
  64.  
  65. printf("Did not converge within %d iterations.\n", MAX_ITER);
  66. return 1;
  67. }
Success #stdin #stdout 0s 5300KB
stdin
Standard input is empty
stdout
Initial guess: x = 1.000000, y = 3.000000
Converged after 4 iterations.
Solution: x = 1.000000, y = 1.732051