zig icon indicating copy to clipboard operation
zig copied to clipboard

`@log2` should work on integers in addition to floats

Open andrewrk opened this issue 3 years ago • 1 comments

const std = @import("std");

const page_size = 4096;

test {
    try std.testing.expect(@log2(page_size) == 12);
}
test.zig:6:34: error: expected vector of floats or float type, found 'comptime_int'
    try std.testing.expect(@log2(page_size) == 12);
                                 ^~~~~~~~~

This code should work, in addition to runtime-known integers. It should return a value whose type has log2 number of bits.

Related: #3321

andrewrk avatar Nov 24 '22 09:11 andrewrk

just like how the integer division in zig (and other modern languages) has been divided into @divExact,@divFloor,@divTrunc etc, it seems like about the same situation here. maybe @ilog2 (sometimes ilogb, what's more, i prefer ulog2) with exact, floor, and maybe also ceil (better definition than "next power of 2")?

mixing them creates ambiguity and possibly confused with floating point log2, making a new quirk (exactly like 5/3==1 in old languages) that i don't think we want to repeat.

what's worse, there's precision problem. because floatN always has less mantissa bits than uintn, for example on float64, log2(2^n-1)=n for n>=49, where trunc can't help.

farteryhr avatar Nov 28 '22 04:11 farteryhr