math.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.precisionAdd = exports.getLogPositiveMin = exports.log = exports.calBase = void 0;
  4. var util_1 = require("@antv/util");
  5. // 求以a为次幂,结果为b的基数,如 x^^a = b;求x
  6. // 虽然数学上 b 不支持负数,但是这里需要支持 负数
  7. function calBase(a, b) {
  8. var e = Math.E;
  9. var value;
  10. if (b >= 0) {
  11. value = Math.pow(e, Math.log(b) / a); // 使用换底公式求底
  12. }
  13. else {
  14. value = Math.pow(e, Math.log(-b) / a) * -1; // 使用换底公式求底
  15. }
  16. return value;
  17. }
  18. exports.calBase = calBase;
  19. function log(a, b) {
  20. if (a === 1) {
  21. return 1;
  22. }
  23. return Math.log(b) / Math.log(a);
  24. }
  25. exports.log = log;
  26. function getLogPositiveMin(values, base, max) {
  27. if (util_1.isNil(max)) {
  28. max = Math.max.apply(null, values);
  29. }
  30. var positiveMin = max;
  31. util_1.each(values, function (value) {
  32. if (value > 0 && value < positiveMin) {
  33. positiveMin = value;
  34. }
  35. });
  36. if (positiveMin === max) {
  37. positiveMin = max / base;
  38. }
  39. if (positiveMin > 1) {
  40. positiveMin = 1;
  41. }
  42. return positiveMin;
  43. }
  44. exports.getLogPositiveMin = getLogPositiveMin;
  45. function digitLength(num) {
  46. // Get digit length of e
  47. var eSplit = num.toString().split(/[eE]/);
  48. var len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0);
  49. return len > 0 ? len : 0;
  50. }
  51. /**
  52. * 高精度加法,解决 0.1 + 0.2 !== 0.3 的经典问题
  53. *
  54. * @param num1 加数
  55. * @param num2 被加数
  56. * @return {number} 返回值
  57. */
  58. function precisionAdd(num1, num2) {
  59. var num1Digits = digitLength(num1);
  60. var num2Digits = digitLength(num2);
  61. var baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
  62. return (num1 * baseNum + num2 * baseNum) / baseNum;
  63. }
  64. exports.precisionAdd = precisionAdd;
  65. //# sourceMappingURL=math.js.map