跳转到内容
标准库Zig 0.17.1官方原文
源码std/math/log2.zig

第 1 行

std.math.log2.builtin

常量

第 2 行

std.math.log2.expect

别名

第 4 行

别名目标 std.testing.expect

std.math.log2.log2

函数

第 13 行

返回 x 的以 2 为底的对数。

特殊情况:

  • log2(+inf) = +inf
  • log2(0) = -inf
  • log2(x) = nan,当 x < 0 时
  • log2(nan) = nan
pub fn log2(x: anytype) @TypeOf(x)

用法示例

test log2 {
    // https://github.com/ziglang/zig/issues/13703
    if (builtin.cpu.arch == .aarch64 and builtin.os.tag == .windows) return error.SkipZigTest;

    try expect(log2(@as(f32, 0.2)) == @log2(0.2));
    try expect(log2(@as(f64, 0.2)) == @log2(0.2));
    comptime {
        try expect(log2(1) == 0);
        try expect(log2(15) == 3);
        try expect(log2(16) == 4);
        try expect(log2(1 << 4073) == 4073);
    }
}

std.math.log2.math

别名

第 3 行

别名目标 std.math

std.math.log2.std

别名

第 1 行

别名目标 std

源码

std/math/log2.zig

const std = @import("../std.zig");
const builtin = @import("builtin");
const math = std.math;
const expect = std.testing.expect;

/// 返回 x 的以 2 为底的对数。
///
/// 特殊情况:
///  - log2(+inf)  = +inf
///  - log2(0)     = -inf
///  - log2(x)     = nan,当 x < 0 时
///  - log2(nan)   = nan
pub fn log2(x: anytype) @TypeOf(x) {
    const T = @TypeOf(x);
    return switch (@typeInfo(T)) {
        .comptime_float, .float => @log2(x),
        .comptime_int => comptime {
            std.debug.assert(x > 0);
            var x_shifted = x;
            // 首先计算 floorPowerOfTwo(x)
            var shift_amt = 1;
            while (x_shifted >> (shift_amt << 1) != 0) shift_amt <<= 1;

            // 答案位于 [shift_amt, 2 * shift_amt - 1] 范围内。
            // 可以使用二分搜索在 O(log(N)) 时间内找到它。
            var result = 0;
            while (shift_amt != 0) : (shift_amt >>= 1) {
                if (x_shifted >> shift_amt != 0) {
                    x_shifted >>= shift_amt;
                    result += shift_amt;
                }
            }
            return result;
        },
        .int => |int_info| math.log2_int(switch (int_info.signedness) {
            .signed => @Int(.unsigned, int_info.bits -| 1),
            .unsigned => T,
        }, @intCast(x)),
        else => @compileError("log2 not implemented for " ++ @typeName(T)),
    };
}

test log2 {
    // https://github.com/ziglang/zig/issues/13703
    if (builtin.cpu.arch == .aarch64 and builtin.os.tag == .windows) return error.SkipZigTest;

    try expect(log2(@as(f32, 0.2)) == @log2(0.2));
    try expect(log2(@as(f64, 0.2)) == @log2(0.2));
    comptime {
        try expect(log2(1) == 0);
        try expect(log2(15) == 3);
        try expect(log2(16) == 4);
        try expect(log2(1 << 4073) == 4073);
    }
}