DoxigAlpha

log

Returns the logarithm of x for the provided base.

Function parameters

Parameters

#
T:type
base:T
x:T

Returns the logarithm of x for the provided base.

Functions

#
log
Returns the logarithm of x for the provided base.

Source

Implementation

#
pub fn log(comptime T: type, base: T, x: T) T {
    if (base == 2) {
        return math.log2(x);
    } else if (base == 10) {
        return math.log10(x);
    } else if ((@typeInfo(T) == .float or @typeInfo(T) == .comptime_float) and base == math.e) {
        return @log(x);
    }

    const float_base = math.lossyCast(f64, base);
    switch (@typeInfo(T)) {
        .comptime_float => {
            return @as(comptime_float, @log(@as(f64, x)) / @log(float_base));
        },

        .comptime_int => {
            return @as(comptime_int, math.log_int(comptime_int, base, x));
        },

        .int => |IntType| switch (IntType.signedness) {
            .signed => @compileError("log not implemented for signed integers"),
            .unsigned => return @as(T, math.log_int(T, base, x)),
        },

        .float => {
            switch (T) {
                f32 => return @as(f32, @floatCast(@log(@as(f64, x)) / @log(float_base))),
                f64 => return @log(x) / @log(float_base),
                else => @compileError("log not implemented for " ++ @typeName(T)),
            }
        },

        else => {
            @compileError("log expects integer or float, found '" ++ @typeName(T) ++ "'");
        },
    }
}