pchip1_test.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. goog.provide('goog.math.interpolator.Pchip1Test');
  15. goog.setTestOnly('goog.math.interpolator.Pchip1Test');
  16. goog.require('goog.math.interpolator.Pchip1');
  17. goog.require('goog.testing.jsunit');
  18. function testSpline() {
  19. var x = [0, 1, 3, 6, 7];
  20. var y = [0, 0, 0, 0, 0];
  21. for (var i = 0; i < x.length; ++i) {
  22. y[i] = Math.sin(x[i]);
  23. }
  24. var interp = new goog.math.interpolator.Pchip1();
  25. interp.setData(x, y);
  26. var xi = [0, 0.5, 1, 2, 3, 4, 5, 6, 7];
  27. var expected =
  28. [0, 0.5756, 0.8415, 0.5428, 0.1411, -0.0595, -0.2162, -0.2794, 0.657];
  29. var result = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  30. for (var i = 0; i < xi.length; ++i) {
  31. result[i] = interp.interpolate(xi[i]);
  32. }
  33. assertElementsRoughlyEqual(expected, result, 1e-4);
  34. }
  35. function testOutOfBounds() {
  36. var x = [0, 1, 2, 4];
  37. var y = [2, 5, 4, 2];
  38. var interp = new goog.math.interpolator.Pchip1();
  39. interp.setData(x, y);
  40. assertRoughlyEquals(-3, interp.interpolate(-1), 1e-4);
  41. assertRoughlyEquals(1, interp.interpolate(5), 1e-4);
  42. }
  43. function testInverse() {
  44. var x = [0, 1, 3, 6, 7];
  45. var y = [0, 2, 7, 8, 10];
  46. var interp = new goog.math.interpolator.Pchip1();
  47. interp.setData(x, y);
  48. var invInterp = interp.getInverse();
  49. var xi = [0, 0.5, 1, 2, 3, 4, 5, 6, 7];
  50. var yi = [0, 0.9548, 2, 4.8938, 7, 7.3906, 7.5902, 8, 10];
  51. var expectedX = [0, 0.888, 1, 0.2852, 3, 4.1206, 4.7379, 6, 7];
  52. var resultX = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  53. var resultY = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  54. for (var i = 0; i < xi.length; ++i) {
  55. resultY[i] = interp.interpolate(xi[i]);
  56. resultX[i] = invInterp.interpolate(yi[i]);
  57. }
  58. assertElementsRoughlyEqual(expectedX, resultX, 1e-4);
  59. assertElementsRoughlyEqual(yi, resultY, 1e-4);
  60. }