pow.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { factory } from '../../utils/factory.js';
  2. import { isInteger } from '../../utils/number.js';
  3. import { arraySize as size } from '../../utils/array.js';
  4. import { powNumber } from '../../plain/number/index.js';
  5. var name = 'pow';
  6. var dependencies = ['typed', 'config', 'identity', 'multiply', 'matrix', 'inv', 'fraction', 'number', 'Complex'];
  7. export var createPow = /* #__PURE__ */factory(name, dependencies, _ref => {
  8. var {
  9. typed,
  10. config,
  11. identity,
  12. multiply,
  13. matrix,
  14. inv,
  15. number,
  16. fraction,
  17. Complex
  18. } = _ref;
  19. /**
  20. * Calculates the power of x to y, `x ^ y`.
  21. *
  22. * Matrix exponentiation is supported for square matrices `x` and integers `y`:
  23. * when `y` is nonnegative, `x` may be any square matrix; and when `y` is
  24. * negative, `x` must be invertible, and then this function returns
  25. * inv(x)^(-y).
  26. *
  27. * For cubic roots of negative numbers, the function returns the principal
  28. * root by default. In order to let the function return the real root,
  29. * math.js can be configured with `math.config({predictable: true})`.
  30. * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.
  31. *
  32. * Syntax:
  33. *
  34. * math.pow(x, y)
  35. *
  36. * Examples:
  37. *
  38. * math.pow(2, 3) // returns number 8
  39. *
  40. * const a = math.complex(2, 3)
  41. * math.pow(a, 2) // returns Complex -5 + 12i
  42. *
  43. * const b = [[1, 2], [4, 3]]
  44. * math.pow(b, 2) // returns Array [[9, 8], [16, 17]]
  45. *
  46. * const c = [[1, 2], [4, 3]]
  47. * math.pow(c, -1) // returns Array [[-0.6, 0.4], [0.8, -0.2]]
  48. *
  49. * See also:
  50. *
  51. * multiply, sqrt, cbrt, nthRoot
  52. *
  53. * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base
  54. * @param {number | BigNumber | Complex} y The exponent
  55. * @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y`
  56. */
  57. return typed(name, {
  58. 'number, number': _pow,
  59. 'Complex, Complex': function ComplexComplex(x, y) {
  60. return x.pow(y);
  61. },
  62. 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
  63. if (y.isInteger() || x >= 0 || config.predictable) {
  64. return x.pow(y);
  65. } else {
  66. return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0);
  67. }
  68. },
  69. 'Fraction, Fraction': function FractionFraction(x, y) {
  70. var result = x.pow(y);
  71. if (result != null) {
  72. return result;
  73. }
  74. if (config.predictable) {
  75. throw new Error('Result of pow is non-rational and cannot be expressed as a fraction');
  76. } else {
  77. return _pow(x.valueOf(), y.valueOf());
  78. }
  79. },
  80. 'Array, number': _powArray,
  81. 'Array, BigNumber': function ArrayBigNumber(x, y) {
  82. return _powArray(x, y.toNumber());
  83. },
  84. 'Matrix, number': _powMatrix,
  85. 'Matrix, BigNumber': function MatrixBigNumber(x, y) {
  86. return _powMatrix(x, y.toNumber());
  87. },
  88. 'Unit, number | BigNumber': function UnitNumberBigNumber(x, y) {
  89. return x.pow(y);
  90. }
  91. });
  92. /**
  93. * Calculates the power of x to y, x^y, for two numbers.
  94. * @param {number} x
  95. * @param {number} y
  96. * @return {number | Complex} res
  97. * @private
  98. */
  99. function _pow(x, y) {
  100. // Alternatively could define a 'realmode' config option or something, but
  101. // 'predictable' will work for now
  102. if (config.predictable && !isInteger(y) && x < 0) {
  103. // Check to see if y can be represented as a fraction
  104. try {
  105. var yFrac = fraction(y);
  106. var yNum = number(yFrac);
  107. if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
  108. if (yFrac.d % 2 === 1) {
  109. return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
  110. }
  111. }
  112. } catch (ex) {
  113. // fraction() throws an error if y is Infinity, etc.
  114. }
  115. // Unable to express y as a fraction, so continue on
  116. }
  117. // **for predictable mode** x^Infinity === NaN if x < -1
  118. // N.B. this behavour is different from `Math.pow` which gives
  119. // (-2)^Infinity === Infinity
  120. if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) {
  121. return NaN;
  122. }
  123. if (isInteger(y) || x >= 0 || config.predictable) {
  124. return powNumber(x, y);
  125. } else {
  126. // TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow
  127. // x^Infinity === 0 if -1 < x < 1
  128. // A real number 0 is returned instead of complex(0)
  129. if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
  130. return 0;
  131. }
  132. return new Complex(x, 0).pow(y, 0);
  133. }
  134. }
  135. /**
  136. * Calculate the power of a 2d array
  137. * @param {Array} x must be a 2 dimensional, square matrix
  138. * @param {number} y a integer value (positive if `x` is not invertible)
  139. * @returns {Array}
  140. * @private
  141. */
  142. function _powArray(x, y) {
  143. if (!isInteger(y)) {
  144. throw new TypeError('For A^b, b must be an integer (value is ' + y + ')');
  145. }
  146. // verify that A is a 2 dimensional square matrix
  147. var s = size(x);
  148. if (s.length !== 2) {
  149. throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');
  150. }
  151. if (s[0] !== s[1]) {
  152. throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');
  153. }
  154. if (y < 0) {
  155. try {
  156. return _powArray(inv(x), -y);
  157. } catch (error) {
  158. if (error.message === 'Cannot calculate inverse, determinant is zero') {
  159. throw new TypeError('For A^b, when A is not invertible, b must be a positive integer (value is ' + y + ')');
  160. }
  161. throw error;
  162. }
  163. }
  164. var res = identity(s[0]).valueOf();
  165. var px = x;
  166. while (y >= 1) {
  167. if ((y & 1) === 1) {
  168. res = multiply(px, res);
  169. }
  170. y >>= 1;
  171. px = multiply(px, px);
  172. }
  173. return res;
  174. }
  175. /**
  176. * Calculate the power of a 2d matrix
  177. * @param {Matrix} x must be a 2 dimensional, square matrix
  178. * @param {number} y a positive, integer value
  179. * @returns {Matrix}
  180. * @private
  181. */
  182. function _powMatrix(x, y) {
  183. return matrix(_powArray(x.valueOf(), y));
  184. }
  185. });