interpolation.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Compute the distance of a value 'v' from 'a' through linear interpolation
  3. * between the values of 'a' and 'b'
  4. *
  5. * Note, that we assume that 'a' and 'b' have unit distance (i.e. 1)
  6. */
  7. function linear(a, b, v) {
  8. if (a < b)
  9. return (v - a) / (b - a);
  10. return (a - v) / (a - b);
  11. }
  12. /*
  13. * Compute the distance of a pair of values ('v0', 'v1') from 'a' through linear interpolation
  14. * between the values of 'a' and 'b'
  15. *
  16. * This function assumes that exactly one value, 'v0' or 'v1', is actually located
  17. * between 'a' and 'b', and choses the right one automagically
  18. *
  19. * Note, that we assume that 'a' and 'b' have unit distance (i.e. 1)
  20. */
  21. function linear_ab(a, b, v0, v1) {
  22. var tmp;
  23. if (v0 > v1) {
  24. tmp = v0;
  25. v0 = v1;
  26. v1 = tmp;
  27. }
  28. if (a < b) {
  29. if (a < v0)
  30. return (v0 - a) / (b - a);
  31. else
  32. return (v1 - a) / (b - a);
  33. } else if (a > v1) {
  34. return (a - v1) / (a - b);
  35. }
  36. return (a - v0) / (a - b);
  37. }
  38. /*
  39. * Compute the distance of a pair of values ('v0', 'v1') from 'a' through linear interpolation
  40. * between the values of 'a' and 'b'
  41. *
  42. * This function automagically choses the value 'vN' that is closer to 'a'
  43. *
  44. * Note, that we assume that 'a' and 'b' have unit distance (i.e. 1)
  45. */
  46. function linear_a(a, b, minV, maxV) {
  47. if (a < b)
  48. return (minV - a) / (b - a);
  49. return (a - maxV) / (a - b);
  50. }
  51. /*
  52. * Compute the distance of a pair of values ('v0', 'v1') from 'a' through linear interpolation
  53. * between the values of 'a' and 'b'
  54. *
  55. * This function automagically choses the value 'vN' that is closer to 'b'
  56. *
  57. * Note, that we assume that 'a' and 'b' have unit distance (i.e. 1)
  58. */
  59. function linear_b(a, b, minV, maxV) {
  60. if (a < b)
  61. return (maxV - a) / (b - a);
  62. return (a - minV) / (a - b);
  63. }
  64. export {
  65. linear,
  66. linear_ab,
  67. linear_a,
  68. linear_b
  69. };