// Returns the natural logarithm of a number.
// @param {Number} $x
// @param {Number} $b The base number
// @example
//     log(2)     // 0.69315
//     log(10)    // 2.30259
//     log(2, 10) // 0.30103
@use "sass:math";

@function log ($x, $b: null) {
    @if $b != null {
        @return math.div(log($x), log($b));
    }

    @if $x <= 0 {
        @return math.div(0, 0);
    }
    $k: nth(frexp(math.div($x, $SQRT2)), 2);
    $x: math.div($x, ldexp(1, $k));

    @return $LN2 * $k + _log($x);
}

// a good aproximation for $x close to 1
@function _log ($x) {
    $x: math.div($x - 1, $x + 1);
    $x2: $x * $x;
    $i: 1;
    $s: $x;
    $sp: null;
    @while $sp != $s {
        $x: $x * $x2;
        $i: $i + 2;
        $sp: $s;
        $s: $s + math.div($x, $i);
    }
    @return 2 * $s;
}
