logBase function

dynamic logBase(
  1. dynamic base,
  2. dynamic x
)

Returns the logarithm of a number to a given base. The logarithm to base b of x is equal to the value y such that b to the power of y is equal to x.

Example:

print(logBase(10, 100));  // Output: 2.0
print(logBase(2, 8));  // Output: 3.0
print(logBase(2, 32));  // Output: 5.0

Example 2:

print(logBase(10, Complex(1, 2)));  // Output: 0.3494850021680094 + 0.480828578784234i
print(logBase(Complex(2, 2), 2));  // Output: 0.4244610654378757 - 0.32063506912468864i
print(logBase(Complex(2, 2), Complex(1, 2)));  // Output: 1.004927367132127 + 0.30573651908857313i

Implementation

dynamic logBase(dynamic base, dynamic x) {
  if ((base is num ||
          base is Decimal) &&
      x is num) {
    num nBase = base is! num ? (base as Decimal).toDouble() : base;
    return math.log(x) / math.log(nBase);
  } else if (base is Complex ||
      x is Complex ||
      base is Imaginary ||
      x is Imaginary) {
    Complex cBase = base is Complex
        ? base
        : base is Imaginary
            ? Complex(0, base)
            : Complex(base, 0);
    Complex cx = x is Complex
        ? x
        : x is Imaginary
            ? Complex(0, x)
            : Complex(x, 0);

    Complex lnBase =
        Complex(math.log(cBase.magnitude), cBase.argument);
    Complex lnX =
        Complex(math.log(cx.magnitude), cx.argument);

    return lnX / lnBase;
  } else {
    throw ArgumentError('Inputs should be either num or Complex');
  }
}