Math.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. (function() {
  2. /**
  3. * Math utility.
  4. * @static
  5. * @constructor
  6. */
  7. tracking.Math = {};
  8. /**
  9. * Euclidean distance between two points P(x0, y0) and P(x1, y1).
  10. * @param {number} x0 Horizontal coordinate of P0.
  11. * @param {number} y0 Vertical coordinate of P0.
  12. * @param {number} x1 Horizontal coordinate of P1.
  13. * @param {number} y1 Vertical coordinate of P1.
  14. * @return {number} The euclidean distance.
  15. */
  16. tracking.Math.distance = function(x0, y0, x1, y1) {
  17. var dx = x1 - x0;
  18. var dy = y1 - y0;
  19. return Math.sqrt(dx * dx + dy * dy);
  20. };
  21. /**
  22. * Calculates the Hamming weight of a string, which is the number of symbols that are
  23. * different from the zero-symbol of the alphabet used. It is thus
  24. * equivalent to the Hamming distance from the all-zero string of the same
  25. * length. For the most typical case, a string of bits, this is the number
  26. * of 1's in the string.
  27. *
  28. * Example:
  29. *
  30. * <pre>
  31. * Binary string Hamming weight
  32. * 11101 4
  33. * 11101010 5
  34. * </pre>
  35. *
  36. * @param {number} i Number that holds the binary string to extract the hamming weight.
  37. * @return {number} The hamming weight.
  38. */
  39. tracking.Math.hammingWeight = function(i) {
  40. i = i - ((i >> 1) & 0x55555555);
  41. i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
  42. return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
  43. };
  44. /**
  45. * Generates a random number between [a, b] interval.
  46. * @param {number} a
  47. * @param {number} b
  48. * @return {number}
  49. */
  50. tracking.Math.uniformRandom = function(a, b) {
  51. return a + Math.random() * (b - a);
  52. };
  53. /**
  54. * Tests if a rectangle intersects with another.
  55. *
  56. * <pre>
  57. * x0y0 -------- x2y2 --------
  58. * | | | |
  59. * -------- x1y1 -------- x3y3
  60. * </pre>
  61. *
  62. * @param {number} x0 Horizontal coordinate of P0.
  63. * @param {number} y0 Vertical coordinate of P0.
  64. * @param {number} x1 Horizontal coordinate of P1.
  65. * @param {number} y1 Vertical coordinate of P1.
  66. * @param {number} x2 Horizontal coordinate of P2.
  67. * @param {number} y2 Vertical coordinate of P2.
  68. * @param {number} x3 Horizontal coordinate of P3.
  69. * @param {number} y3 Vertical coordinate of P3.
  70. * @return {boolean}
  71. */
  72. tracking.Math.intersectRect = function(x0, y0, x1, y1, x2, y2, x3, y3) {
  73. return !(x2 > x1 || x3 < x0 || y2 > y1 || y3 < y0);
  74. };
  75. }());