Guest User

Untitled

a guest
Sep 28th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. /**
  2. * At least two points are needed to interpolate something.
  3. * @class Lagrange polynomial interpolation.
  4. * The computed interpolation polynomial will be reffered to as L(x).
  5. * @example
  6. * var l = new Lagrange(0, 0, 1, 1);
  7. * var index = l.addPoint(0.5, 0.8);
  8. * console.log(l.valueOf(0.1));
  9. *
  10. * l.changePoint(index, 0.5, 0.1);
  11. * console.log(l.valueOf(0.1));
  12. */
  13. var Lagrange = function(x1, y1, x2, y2) {
  14.  
  15. this.xs = [x1, x2];
  16. this.ys = [y1, y2];
  17. this.ws = [];
  18. this._updateWeights();
  19. }
  20.  
  21. /**
  22. * Adds a new point to the polynomial. L(x) = y
  23. * @return {Number} The index of the added point. Used for changing the point. See changePoint.
  24. */
  25. Lagrange.prototype.addPoint = function(x, y) {
  26. this.xs.push(x);
  27. this.ys.push(y);
  28. this._updateWeights();
  29. return this.xs.length-1;
  30. }
  31.  
  32. /**
  33. * Changes a previously added point.
  34. */
  35. Lagrange.prototype.changePoint = function(index, x, y) {
  36. this.xs[index] = x;
  37. this.ys[index] = y;
  38. this._updateWeights();
  39. }
  40.  
  41. /**
  42. * Recalculate barycentric weights.
  43. */
  44. Lagrange.prototype._updateWeights = function() {
  45. var k = this.xs.length;
  46. var w;
  47.  
  48. for (var j = 0; j < k; ++j) {
  49. w = 1;
  50. for (var i = 0; i < k; ++i) {
  51. if (i != j) {
  52. w *= this.xs[j] - this.xs[i];
  53. }
  54. }
  55. this.ws[j] = 1/w;
  56. }
  57. }
  58.  
  59. /**
  60. * Calculate L(x)
  61. */
  62. Lagrange.prototype.valueOf = function(x) {
  63. var a = 0;
  64. var b = 0;
  65. var c = 0;
  66.  
  67. for (var j = 0; j < this.xs.length; ++j) {
  68. if (x != this.xs[j]) {
  69. a = this.ws[j] / (x - this.xs[j]);
  70. b += a * this.ys[j];
  71. c += a;
  72. } else {
  73. return this.ys[j];
  74. }
  75. }
  76.  
  77. return b / c;
  78. }
Add Comment
Please, Sign In to add comment