log function
dynamic
log(
- dynamic x, [
- dynamic b
Returns the logarithm (base b) of x.
If b is null, then it returns the natural logarithm of a number.
Throws an ArgumentError if x or b is less than or equal to 0.
Example 1:
print(log(100, 10)); // prints: 2.0
Example 2:
print(log(math.e)); // Output: 1.0
Example 3:
print(log(Matrix([[1, 2], [3, 4]]))); // Output: [[0.6931471805599453, 1.039720770839918], [1.559581156259877, 1.7404683910198387]]
Implementation
dynamic log(dynamic x, [dynamic b]) {
if (x is Rational) x = x.toDouble();
if (b is Rational) b = b.toDouble();
if (x is num || x is Decimal) {
num nx = x is! num ? (x as Decimal).toDouble() : x;
if (nx <= 0 || (b != null && b <= 0)) {
throw ArgumentError('Invalid input for log: n and b must be > 0');
}
return b != null ? math.log(nx) / math.log(b) : math.log(nx);
} else if (x is Complex || x is Imaginary) {
Complex nx = x is Complex ? x : Complex(0, x);
Complex lnZ = Complex(math.log(nx.magnitude), nx.argument.real);
if (b == null) {
return lnZ;
} else if (b is num) {
if (b <= 0) {
throw ArgumentError('Invalid input for log: b must be > 0');
}
return lnZ / math.log(b);
} else if (b is Complex) {
return lnZ / log(b);
} else {
throw ArgumentError('Invalid base type for log');
}
} else if (x is Matrix) {
return MatrixFunctions(x).log();
} else {
throw ArgumentError('Input should be either num or Complex');
}
}