/*
Return a new Decimal whose value is the natural logarithm of `x` truncated to `sd` significant
digits.

ln(n) is non-terminating (n != 1)
10156
function ln(y, sd) {
    var c, c0, denominator, e, numerator, sum, t, wpr, x2,
      n = 1,
      guard = 10,
      x = y,
      xd = x.d,
      Ctor = x.constructor,
      pr = Ctor.precision;

    // ln(-x) = NaN
    // ln(0) = -Infinity
    if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));

    // ln(1) = 0
    if (x.eq(ONE)) return new Ctor(0);

    if (sd == null) {
      external = false;
      wpr = pr;
    } else {
      wpr = sd;
    }

    if (x.eq(10)) {
      if (sd == null) external = true;
      return getLn10(Ctor, wpr);
    }

    wpr += guard;
    Ctor.precision = wpr;
    c = digitsToString(xd);
    c0 = c.charAt(0);
    e = getBase10Exponent(x);

    if (Math.abs(e) < 1.5e15) {

      // Argument reduction.
      // The series converges faster the closer the argument is to 1, so using
      // ln(a^b) = b * ln(a),   ln(a) = ln(a^b) / b
      // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
      // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
      // later be divided by this number, then separate out the power of 10 using
      // ln(a*10^b) = ln(a) + b*ln(10).

      // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
      //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
      // max n is 6 (gives 0.7 - 1.3)
      while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
        x = x.times(y);
        c = digitsToString(x.d);
        c0 = c.charAt(0);
        n++;
      }

      e = getBase10Exponent(x);

      if (c0 > 1) {
        x = new Ctor('0.' + c);
        e++;
      } else {
        x = new Ctor(c0 + '.' + c.slice(1));
      }
    } else {

      // The argument reduction method above may result in overflow if the argument y is a massive
      // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
      // function using ln(x*10^e) = ln(x) + e*ln(10).
      t = getLn10(Ctor, wpr + 2, pr).times(e + '');
      x = ln(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);

      Ctor.precision = pr;
      return sd == null ? (external = true, round(x, pr)) : x;
    }

    // x is reduced to a value near 1.

    // Taylor series.
    // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
    // where x = (y - 1)/(y + 1)    (|x| < 1)
    sum = numerator = x = divide(x.minus(ONE), x.plus(ONE), wpr);
    x2 = round(x.times(x), wpr);
    denominator = 3;

    for (;;) {
      numerator = round(numerator.times(x2), wpr);
      t = sum.plus(divide(numerator, new Ctor(denominator), wpr));

      if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
        sum = sum.times(2);

        // Reverse the argument reduction.
        if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
        sum = divide(sum, new Ctor(n), wpr);

        Ctor.precision = pr;
        return sd == null ? (external = true, round(sum, pr)) : sum;
      }

      sum = t;
      denominator += 2;
    }
  }
688740
public static Decimal fromBigDecimal(BigDecimal bd, int precision, int scale) {
		bd = bd.setScale(scale, RoundingMode.HALF_UP);
		if (bd.precision() > precision) {
			return null;
		}

		long longVal = -1;
		if (precision <= MAX_COMPACT_PRECISION) {
			longVal = bd.movePointRight(scale).longValueExact();
		}
		return new Decimal(precision, scale, longVal, bd);
	}
609627
public static BigDecimal logRangeTen(BigDecimal x, MathContext mathContext, BiFunction<BigDecimal, MathContext, BigDecimal> logFunction) {
		// http://en.wikipedia.org/wiki/Natural_logarithm

		if (x.signum() <= 0) {
			throw new ArithmeticException("Illegal log(x) for x <= 0: x = " + x);
		}
		if (x.compareTo(ONE) == 0) {
			return ZERO;
		}

		switch (x.compareTo(TEN)) {
			case 0:
				return logTen(mathContext);
			case 1:
				return logUsingExponent(x, mathContext, logFunction);
		}

		return logFunction.apply(x, mathContext);
	}
1026534
function parseDecimal(x, str) {
    var e, i, len;

    // Decimal point?
    if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');

    // Exponential form?
    if ((i = str.search(/e/i)) > 0) {

      // Determine exponent.
      if (e < 0) e = i;
      e += +str.slice(i + 1);
      str = str.substring(0, i);
    } else if (e < 0) {

      // Integer.
      e = str.length;
    }

    // Determine leading zeros.
    for (i = 0; str.charCodeAt(i) === 48;) ++i;

    // Determine trailing zeros.
    for (len = str.length; str.charCodeAt(len - 1) === 48;) --len;
    str = str.slice(i, len);

    if (str) {
      len -= i;
      e = e - i - 1;
      x.e = mathfloor(e / LOG_BASE);
      x.d = [];

      // Transform base

      // e is the base 10 exponent.
      // i is where to slice str to get the first word of the digits array.
      i = (e + 1) % LOG_BASE;
      if (e < 0) i += LOG_BASE;

      if (i < len) {
        if (i) x.d.push(+str.slice(0, i));
        for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
        str = str.slice(i);
        i = LOG_BASE - str.length;
      } else {
        i -= len;
      }

      for (; i--;) str += '0';
      x.d.push(+str);

      if (external && (x.e > MAX_E || x.e < -MAX_E)) throw Error(exponentOutOfRange + e);
    } else {

      // Zero.
      x.s = 0;
      x.e = 0;
      x.d = [0];
    }

    return x;
  }
1150046
function dtlog(df) {
      var t;

      t = -bd0(df / 2, (df + 1) / 2) + stirlerr((df + 1) / 2) - stirlerr(df / 2);
      return function(x) {
         var x2n, logx2n, u;

         if (utils.hasNaN(x, df) || df <= 0) { return NaN; }

         x2n = x * x / df;
         logx2n = Math.log(1 + x2n) / 2;
         u = x2n > 0.2 ? df * logx2n
                       : x * x / 2 - bd0(df / 2, (df + x * x) / 2);
         return t - u - (logx2n + Math.log(sqrt2pi));
      };
   }
272044
@Override 
    public double fromReal(double x) {
        long sign = POSITIVE;
        if (x < 0) {
            sign = NEGATIVE;
            x = -x;  
        }
        return compact(sign, FastMath.log(x));
    }
1333568
function decCoefficientToBinaryString (x) {
  // Convert to string
  const a = x.d // array with digits
  let r = a[0] + ''

  for (let i = 1; i < a.length; ++i) {
    let s = a[i] + ''
    for (let z = 7 - s.length; z--;) {
      s = '0' + s
    }

    r += s
  }

  let j = r.length
  while (r.charAt(j) === '0') {
    j--
  }

  let xe = x.e
  let str = r.slice(0, j + 1 || 1)
  const strL = str.length
  if (xe > 0) {
    if (++xe > strL) {
      // Append zeros.
      xe -= strL
      while (xe--) {
        str += '0'
      }
    } else if (xe < strL) {
      str = str.slice(0, xe) + '.' + str.slice(xe)
    }
  }

  // Convert from base 10 (decimal) to base 2
  const arr = [0]
  for (let i = 0; i < str.length;) {
    let arrL = arr.length
    while (arrL--) {
      arr[arrL] *= 10
    }

    arr[0] += parseInt(str.charAt(i++)) // convert to int
    for (let j = 0; j < arr.length; ++j) {
      if (arr[j] > 1) {
        if (arr[j + 1] === null || arr[j + 1] === undefined) {
          arr[j + 1] = 0
        }

        arr[j + 1] += arr[j] >> 1
        arr[j] &= 1
      }
    }
  }

  return arr.reverse()
}
706025
def trunc(ctx, number):
    
    return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_DOWN), ctx)
823239
function decimal(_num, _precision) {

	// If _num is undefined, assing 0	
	if(_num === undefined) _num = 0;
	
	// If _precision is undefined, assigned 2
	if(_precision === undefined) _num = 2;

    n = Math.abs(_num);
    
    var sign = '';
    if(_num < 0)
    	sign = '-';
    	
    return sign + n.toFixed(_precision);
}
1018200
function getDigitCount(value) {
  let result;

  if (value === 0) {
    result = 1;
  } else {
    result = Math.floor(new Decimal(value).abs().log(10)
      .toNumber()) + 1;
  }

  return result;
}
1308157
def truncate(num, precision=0):
        """"""
        if precision > 0:
            decimal_precision = math.pow(10, precision)
            return math.trunc(num * decimal_precision) / decimal_precision
        return int(Exchange.truncate_to_string(num, precision))
1263344
def nice_log(x):
    
    neg = x < 0
    xi = np.log2(np.abs(x) + 1)
    xi[neg] = -xi[neg]
    return xi
827222
private static double logSumExp(double[] x) {
    double max = x[0];
    for(int i = 1; i < x.length; i++) {
      final double v = x[i];
      max = v > max ? v : max;
    }
    final double cutoff = max - 35.350506209; // log_e(2**51)
    double acc = 0.;
    for(int i = 0; i < x.length; i++) {
      final double v = x[i];
      if(v > cutoff) {
        acc += v < max ? FastMath.exp(v - max) : 1.;
      }
    }
    return acc > 1. ? (max + FastMath.log(acc)) : max;
  }
1070885
static int longDigitLength(long x) {
        /*
         * As described in "Bit Twiddling Hacks" by Sean Anderson,
         * (http://graphics.stanford.edu/~seander/bithacks.html)
         * integer log 10 of x is within 1 of (1233/4096)* (1 +
         * integer log 2 of x). The fraction 1233/4096 approximates
         * log10(2). So we first do a version of log2 (a variant of
         * Long class with pre-checks and opposite directionality) and
         * then scale and check against powers table. This is a little
         * simpler in present context than the version in Hacker's
         * Delight sec 11-4. Adding one to bit length allows comparing
         * downward from the LONG_TEN_POWERS_TABLE that we need
         * anyway.
         */
        assert x != BigDecimal.INFLATED;
        if (x < 0)
            x = -x;
        if (x < 10) // must screen for 0, might as well 10
            return 1;
        int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;
        long[] tab = LONG_TEN_POWERS_TABLE;
        // if r >= length, must have max possible digits for long
        return (r >= tab.length || x < tab[r]) ? r : r + 1;
    }
615310
private short expectedExponent() {
        // since the log of 0, or the log base 0 of something, causes an
        // error, declare the exponent in these cases to be 0 (we also
        // deal with the special-rule identifiers here)
        if (radix == 0 || baseValue < 1) {
            return 0;
        }

        // we get rounding error in some cases-- for example, log 1000 / log 10
        // gives us 1.9999999996 instead of 2.  The extra logic here is to take
        // that into account
        short tempResult = (short)(Math.log(baseValue) / Math.log(radix));
        if (power(radix, (short)(tempResult + 1)) <= baseValue) {
            return (short)(tempResult + 1);
        } else {
            return tempResult;
        }
    }
1305759
public static BigFloat log(BigFloat x) {
		BigFloat temp = logSpecial(x);
		return temp != null ? temp : x.context.valueOf(BigDecimalMath.log(x.value, x.context.mathContext));
	}
340829
function lchoose(n, k) {
      k = Math.round(k);
      if (utils.hasNaN(n, k)) { return NaN; }
      if (k < 0) { return -Infinity; }
      if (k === 0) { return 0; }
      if (k === 1) { return Math.log(Math.abs(n)); }
      if (n < 0) { return lchoose(-n + k - 1, k); }
      if (n === Math.round(n)) {
         if (n < k) { return -Infinity; }
         if (n - k < 2) { return lchoose(n, n - k); }

         return lfastchoose(n, k);
      }
      if (n < k - 1) { return lfastchoose2(n, k); }

      return lfastchoose(n, k);
   }