跳转到内容

std.math.isnormal

标准库Zig 0.17.1官方原文
源码std/math/isnormal.zig

第 1 行

std.math.isnormal.expect

别名

第 3 行

别名目标 std.testing.expect

std.math.isnormal.isNormal

函数

第 6 行

返回 x 是否既非零、非次正规数、非无穷,也非 NaN。

pub fn isNormal(x: anytype) bool

用法示例

test isNormal {
    // TODO: math.inf(T) 支持后,添加 `c_longdouble' 类型
    inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
        const TBits = @Int(.unsigned, @bitSizeOf(T));

        // 正规数
        try expect(isNormal(@as(T, 1.0)));
        try expect(isNormal(math.floatMin(T)));
        try expect(isNormal(math.floatMax(T)));

        // 次正规数
        try expect(!isNormal(@as(T, -0.0)));
        try expect(!isNormal(@as(T, 0.0)));
        try expect(!isNormal(@as(T, math.floatTrueMin(T))));

        // 最大的次正规数
        try expect(!isNormal(@as(T, @bitCast(~(~@as(TBits, 0) << math.floatFractionalBits(T))))));

        // 非有限数
        try expect(!isNormal(-math.inf(T)));
        try expect(!isNormal(math.inf(T)));
        try expect(!isNormal(math.nan(T)));

        // 溢出边界情况(实现中有所说明,另见 #10133)。
        try expect(!isNormal(@as(T, @bitCast(~@as(TBits, 0)))));
    }
}

std.math.isnormal.math

别名

第 2 行

别名目标 std.math

std.math.isnormal.std

别名

第 1 行

别名目标 std

源码

std/math/isnormal.zig

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

/// 返回 x 是否既非零、非次正规数、非无穷,也非 NaN。
pub fn isNormal(x: anytype) bool {
    const T = @TypeOf(x);
    const TBits = @Int(.unsigned, @typeInfo(T).float.bits);

    const increment_exp = 1 << math.floatMantissaBits(T);
    const remove_sign = ~@as(TBits, 0) >> 1;

    // 将指数加 1,如果溢出为 0 或变成 1,
    // 则它原本全为零,即次正规数,或全为一,即特殊值 inf/nan。
    // 移除符号位,因为全一时会溢出到该位。
    // 对于 f80,虽然显式存储了整数部分,
    // 但两者不一致时,实际上以指数为准。
    const value = @as(TBits, @bitCast(x)) +% increment_exp;
    return value & remove_sign >= (increment_exp << 1);
}

test isNormal {
    // TODO: math.inf(T) 支持后,添加 `c_longdouble' 类型
    inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
        const TBits = @Int(.unsigned, @bitSizeOf(T));

        // 正规数
        try expect(isNormal(@as(T, 1.0)));
        try expect(isNormal(math.floatMin(T)));
        try expect(isNormal(math.floatMax(T)));

        // 次正规数
        try expect(!isNormal(@as(T, -0.0)));
        try expect(!isNormal(@as(T, 0.0)));
        try expect(!isNormal(@as(T, math.floatTrueMin(T))));

        // 最大的次正规数
        try expect(!isNormal(@as(T, @bitCast(~(~@as(TBits, 0) << math.floatFractionalBits(T))))));

        // 非有限数
        try expect(!isNormal(-math.inf(T)));
        try expect(!isNormal(math.inf(T)));
        try expect(!isNormal(math.nan(T)));

        // 溢出边界情况(实现中有所说明,另见 #10133)。
        try expect(!isNormal(@as(T, @bitCast(~@as(TBits, 0)))));
    }
}