hesse-convergence.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. Fraction.js v5.0.0 10/1/2024
  3. https://raw.org/article/rational-numbers-in-javascript/
  4. Copyright (c) 2024, Robert Eisele (https://raw.org/)
  5. Licensed under the MIT license.
  6. */
  7. const Fraction = require('fraction.js');
  8. /*
  9. We have the polynom f(x) = 1/3x_1^2 + x_2^2 + x_1 * x_2 + 3
  10. The gradient of f(x):
  11. grad(x) = | x_1^2+x_2 |
  12. | 2x_2+x_1 |
  13. And thus the Hesse-Matrix H:
  14. | 2x_1 1 |
  15. | 1 2 |
  16. The inverse Hesse-Matrix H^-1 is
  17. | -2 / (1-4x_1) 1 / (1 - 4x_1) |
  18. | 1 / (1 - 4x_1) -2x_1 / (1 - 4x_1) |
  19. We now want to find lim ->oo x[n], with the starting element of (3 2)^T
  20. */
  21. // Get the Hesse Matrix
  22. function H(x) {
  23. var z = Fraction(1).sub(Fraction(4).mul(x[0]));
  24. return [
  25. Fraction(-2).div(z),
  26. Fraction(1).div(z),
  27. Fraction(1).div(z),
  28. Fraction(-2).mul(x[0]).div(z),
  29. ];
  30. }
  31. // Get the gradient of f(x)
  32. function grad(x) {
  33. return [
  34. Fraction(x[0]).mul(x[0]).add(x[1]),
  35. Fraction(2).mul(x[1]).add(x[0])
  36. ];
  37. }
  38. // A simple matrix multiplication helper
  39. function matrMult(m, v) {
  40. return [
  41. Fraction(m[0]).mul(v[0]).add(Fraction(m[1]).mul(v[1])),
  42. Fraction(m[2]).mul(v[0]).add(Fraction(m[3]).mul(v[1]))
  43. ];
  44. }
  45. // A simple vector subtraction helper
  46. function vecSub(a, b) {
  47. return [
  48. Fraction(a[0]).sub(b[0]),
  49. Fraction(a[1]).sub(b[1])
  50. ];
  51. }
  52. // Main function, gets a vector and the actual index
  53. function run(V, j) {
  54. var t = H(V);
  55. //console.log("H(X)");
  56. for (var i in t) {
  57. // console.log(t[i].toFraction());
  58. }
  59. var s = grad(V);
  60. //console.log("vf(X)");
  61. for (var i in s) {
  62. // console.log(s[i].toFraction());
  63. }
  64. //console.log("multiplication");
  65. var r = matrMult(t, s);
  66. for (var i in r) {
  67. // console.log(r[i].toFraction());
  68. }
  69. var R = (vecSub(V, r));
  70. console.log("X" + j);
  71. console.log(R[0].toFraction(), "= " + R[0].valueOf());
  72. console.log(R[1].toFraction(), "= " + R[1].valueOf());
  73. console.log("\n");
  74. return R;
  75. }
  76. // Set the starting vector
  77. var v = [3, 2];
  78. for (var i = 0; i < 15; i++) {
  79. v = run(v, i);
  80. }