simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

log2.js (2054B)


      1 import { factory } from '../../utils/factory.js';
      2 import { deepMap } from '../../utils/collection.js';
      3 import { log2Number } from '../../plain/number/index.js';
      4 var name = 'log2';
      5 var dependencies = ['typed', 'config', 'Complex'];
      6 export var createLog2 = /* #__PURE__ */factory(name, dependencies, _ref => {
      7   var {
      8     typed,
      9     config,
     10     Complex
     11   } = _ref;
     12 
     13   /**
     14    * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.
     15    *
     16    * For matrices, the function is evaluated element wise.
     17    *
     18    * Syntax:
     19    *
     20    *    math.log2(x)
     21    *
     22    * Examples:
     23    *
     24    *    math.log2(0.03125)           // returns -5
     25    *    math.log2(16)                // returns 4
     26    *    math.log2(16) / math.log2(2) // returns 4
     27    *    math.pow(2, 4)               // returns 16
     28    *
     29    * See also:
     30    *
     31    *    exp, log, log1p, log10
     32    *
     33    * @param {number | BigNumber | Complex | Array | Matrix} x
     34    *            Value for which to calculate the logarithm.
     35    * @return {number | BigNumber | Complex | Array | Matrix}
     36    *            Returns the 2-base logarithm of `x`
     37    */
     38   return typed(name, {
     39     number: function number(x) {
     40       if (x >= 0 || config.predictable) {
     41         return log2Number(x);
     42       } else {
     43         // negative value -> complex value computation
     44         return _log2Complex(new Complex(x, 0));
     45       }
     46     },
     47     Complex: _log2Complex,
     48     BigNumber: function BigNumber(x) {
     49       if (!x.isNegative() || config.predictable) {
     50         return x.log(2);
     51       } else {
     52         // downgrade to number, return Complex valued result
     53         return _log2Complex(new Complex(x.toNumber(), 0));
     54       }
     55     },
     56     'Array | Matrix': function ArrayMatrix(x) {
     57       return deepMap(x, this);
     58     }
     59   });
     60   /**
     61    * Calculate log2 for a complex value
     62    * @param {Complex} x
     63    * @returns {Complex}
     64    * @private
     65    */
     66 
     67   function _log2Complex(x) {
     68     var newX = Math.sqrt(x.re * x.re + x.im * x.im);
     69     return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2);
     70   }
     71 });