log1p.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { factory } from '../../utils/factory.js';
  2. import { deepMap } from '../../utils/collection.js';
  3. import { log1p as _log1p } from '../../utils/number.js';
  4. var name = 'log1p';
  5. var dependencies = ['typed', 'config', 'divideScalar', 'log', 'Complex'];
  6. export var createLog1p = /* #__PURE__ */factory(name, dependencies, _ref => {
  7. var {
  8. typed,
  9. config,
  10. divideScalar,
  11. log,
  12. Complex
  13. } = _ref;
  14. /**
  15. * Calculate the logarithm of a `value+1`.
  16. *
  17. * For matrices, the function is evaluated element wise.
  18. *
  19. * Syntax:
  20. *
  21. * math.log1p(x)
  22. * math.log1p(x, base)
  23. *
  24. * Examples:
  25. *
  26. * math.log1p(2.5) // returns 1.252762968495368
  27. * math.exp(math.log1p(1.4)) // returns 2.4
  28. *
  29. * math.pow(10, 4) // returns 10000
  30. * math.log1p(9999, 10) // returns 4
  31. * math.log1p(9999) / math.log(10) // returns 4
  32. *
  33. * See also:
  34. *
  35. * exp, log, log2, log10
  36. *
  37. * @param {number | BigNumber | Complex | Array | Matrix} x
  38. * Value for which to calculate the logarithm of `x+1`.
  39. * @param {number | BigNumber | Complex} [base=e]
  40. * Optional base for the logarithm. If not provided, the natural
  41. * logarithm of `x+1` is calculated.
  42. * @return {number | BigNumber | Complex | Array | Matrix}
  43. * Returns the logarithm of `x+1`
  44. */
  45. return typed(name, {
  46. number: function number(x) {
  47. if (x >= -1 || config.predictable) {
  48. return _log1p(x);
  49. } else {
  50. // negative value -> complex value computation
  51. return _log1pComplex(new Complex(x, 0));
  52. }
  53. },
  54. Complex: _log1pComplex,
  55. BigNumber: function BigNumber(x) {
  56. var y = x.plus(1);
  57. if (!y.isNegative() || config.predictable) {
  58. return y.ln();
  59. } else {
  60. // downgrade to number, return Complex valued result
  61. return _log1pComplex(new Complex(x.toNumber(), 0));
  62. }
  63. },
  64. 'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self)),
  65. 'any, any': typed.referToSelf(self => (x, base) => {
  66. // calculate logarithm for a specified base, log1p(x, base)
  67. return divideScalar(self(x), log(base));
  68. })
  69. });
  70. /**
  71. * Calculate the natural logarithm of a complex number + 1
  72. * @param {Complex} x
  73. * @returns {Complex}
  74. * @private
  75. */
  76. function _log1pComplex(x) {
  77. var xRe1p = x.re + 1;
  78. return new Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p));
  79. }
  80. });