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

第 1 行

std.math.float.assert

别名

第 3 行

别名目标 std.debug.assert

std.math.float.builtin

常量

第 2 行

std.math.float.expect

别名

第 4 行

别名目标 std.testing.expect

std.math.float.expectEqual

别名

第 5 行

别名目标 std.testing.expectEqual

std.math.float.floatBits

函数

第 303 行

fn floatBits(comptime Type: type) !void

参数

Type: type

用法示例

test floatBits {
    try floatBits(f16);
    try floatBits(f32);
    try floatBits(f64);
    try floatBits(f80);
    try floatBits(f128);
    try floatBits(c_longdouble);
}

std.math.float.floatEps

函数

第 248 行

返回浮点类型 T 的机器 epsilon。

pub inline fn floatEps(comptime T: type) T

参数

T: type

std.math.float.floatEpsAt

函数

第 253 行

返回浮点类型 T 的局部 epsilon。

pub inline fn floatEpsAt(comptime T: type, x: T) T

参数

T: type
x: T

std.math.float.floatExponentBits

函数

第 175 行

返回浮点类型 T 的指数位数。

pub inline fn floatExponentBits(comptime T: type) comptime_int

参数

T: type

std.math.float.floatExponentMax

函数

第 227 行

返回浮点类型 T 中可以表示 正规值的最大指数。

pub inline fn floatExponentMax(comptime T: type) comptime_int

参数

T: type

std.math.float.floatExponentMin

函数

第 221 行

返回浮点类型 T 可表示 正规值的最小指数。

pub inline fn floatExponentMin(comptime T: type) comptime_int

参数

T: type

std.math.float.floatFractionalBits

函数

第 203 行

返回浮点类型 T 尾数中的小数位数。

pub inline fn floatFractionalBits(comptime T: type) comptime_int

参数

T: type

std.math.float.floatMantissaBits

函数

第 189 行

返回浮点类型 T 的尾数位数。

pub inline fn floatMantissaBits(comptime T: type) comptime_int

参数

T: type

std.math.float.floatMax

函数

第 242 行

返回浮点类型 T 可表示的最大正规数。

pub inline fn floatMax(comptime T: type) T

参数

T: type

std.math.float.floatMin

函数

第 237 行

返回浮点类型 T 可表示的最小正规数。

pub inline fn floatMin(comptime T: type) T

参数

T: type

std.math.float.FloatRepr

类型函数

第 69 行

pub fn FloatRepr(comptime Float: type) type

参数

Float: type

字段

mantissa: StoredMantissa
exponent: BiasedExponent
sign: std.math.Sign

std.math.float.FloatRepr.BiasedExponent

容器

第 82 行

字段

denormal = 0
min_normal = 1
zero = (1 << (exponent_bits - 1)) - 1
max_normal = (1 << exponent_bits) - 2
infinite = (1 << exponent_bits) - 1
_

std.math.float.FloatRepr.BiasedExponent.bias

函数

第 100 行

pub fn bias(unbiased: Exponent) BiasedExponent

参数

unbiased: Exponent

std.math.float.FloatRepr.BiasedExponent.Int

常量

第 90 行

std.math.float.FloatRepr.BiasedExponent.unbias

函数

第 92 行

pub fn unbias(biased: BiasedExponent) Exponent

参数

biased: BiasedExponent

std.math.float.FloatRepr.Classified

容器

第 138 行

字段

normalized: Normalized
infinity
nan
invalid

std.math.float.FloatRepr.classify

函数

第 139 行

fn classify(repr: Repr) Classified

参数

repr: Repr

std.math.float.FloatRepr.Exponent

常量

第 81 行

std.math.float.FloatRepr.Mantissa

常量

第 80 行

std.math.float.FloatRepr.Normalized

容器

第 105 行

字段

fraction: Fraction
exponent: Normalized.Exponent

std.math.float.FloatRepr.Normalized.Exponent

常量

第 110 行

std.math.float.FloatRepr.Normalized.Fraction

常量

第 109 行

std.math.float.FloatRepr.Normalized.reconstruct

函数

第 114 行

此实现目前截断非正规值;在可用于生成舍入值之前,需要先修复该问题。

pub fn reconstruct(normalized: Normalized, sign: std.math.Sign) Float

参数

normalized: Normalized
sign: std.math.Sign

std.math.float.FloatRepr.Repr

别名

第 73 行

别名目标 std.math.float.FloatRepr

std.math.float.FloatRepr.StoredMantissa

常量

第 79 行

std.math.float.floatTrueMin

函数

第 232 行

返回浮点类型 T 可表示的最小非正规数。

pub inline fn floatTrueMin(comptime T: type) T

参数

T: type

std.math.float.inf

函数

第 266 行

返回浮点 Type 的无穷值。

pub inline fn inf(comptime Type: type) Type

参数

Type: type

用法示例

test inf {
    const inf_u16: u16 = 0x7C00;
    const inf_u32: u32 = 0x7F800000;
    const inf_u64: u64 = 0x7FF0000000000000;
    const inf_u80: u80 = 0x7FFF8000000000000000;
    const inf_u128: u128 = 0x7FFF0000000000000000000000000000;
    try expectEqual(inf_u16, @as(u16, @bitCast(inf(f16))));
    try expectEqual(inf_u32, @as(u32, @bitCast(inf(f32))));
    try expectEqual(inf_u64, @as(u64, @bitCast(inf(f64))));
    try expectEqual(inf_u80, @as(u80, @bitCast(inf(f80))));
    try expectEqual(inf_u128, @as(u128, @bitCast(inf(f128))));
}

std.math.float.long_double

命名空间

第 10 行

用于处理精度高于双精度的浮点类型 (f80、f128、c_longdouble)的函数命名空间。 在 C 中通常称为 long double。

std.math.float.long_double.bitWidth

函数

第 13 行

inline fn bitWidth(x: anytype) u16

std.math.float.long_double.mantissaTop

函数

第 46 行

取 long double 尾数的最高 16 位。

pub fn mantissaTop(x: anytype) u16

std.math.float.long_double.signExponent

函数

第 22 行

返回 long double 的符号位和指数位。

pub fn signExponent(x: anytype) u16

std.math.float.long_double.U80

常量

第 11 行

std.math.float.mantissaOne

函数

第 163 行

为浮点类型 T 创建原始的 "1.0" 尾数,用于消除重复的 f80 逻辑。

inline fn mantissaOne(comptime T: type) comptime_int

参数

T: type

std.math.float.nan

函数

第 275 行

返回浮点 Type 的规范静默 NaN 表示。

pub inline fn nan(comptime Type: type) Type

参数

Type: type

用法示例

test nan {
    const qnan_u16: u16 = 0x7E00;
    const qnan_u32: u32 = 0x7FC00000;
    const qnan_u64: u64 = 0x7FF8000000000000;
    const qnan_u80: u80 = 0x7FFFC000000000000000;
    const qnan_u128: u128 = 0x7FFF8000000000000000000000000000;
    try expectEqual(qnan_u16, @as(u16, @bitCast(nan(f16))));
    try expectEqual(qnan_u32, @as(u32, @bitCast(nan(f32))));
    try expectEqual(qnan_u64, @as(u64, @bitCast(nan(f64))));
    try expectEqual(qnan_u80, @as(u80, @bitCast(nan(f80))));
    try expectEqual(qnan_u128, @as(u128, @bitCast(nan(f128))));
}

std.math.float.reconstructFloat

函数

第 168 行

根据无偏指数和原始尾数创建浮点类型 T 的值。

inline fn reconstructFloat(comptime T: type, comptime exponent: comptime_int, comptime mantissa: comptime_int) T

参数

T: type
exponent: comptime_int
mantissa: comptime_int

std.math.float.snan

函数

第 291 行

返回浮点 Type 的信号 NaN 表示。

TODO: 已知 LLVM 在某些架构上会将其错误编译为静默 NaN; 跟踪问题:https://github.com/ziglang/zig/issues/14366

pub inline fn snan(comptime Type: type) Type

参数

Type: type

用法示例

test snan {
    const snan_u16: u16 = 0x7D00;
    const snan_u32: u32 = 0x7FA00000;
    const snan_u64: u64 = 0x7FF4000000000000;
    const snan_u80: u80 = 0x7FFFA000000000000000;
    const snan_u128: u128 = 0x7FFF4000000000000000000000000000;
    try expectEqual(snan_u16, @as(u16, @bitCast(snan(f16))));
    try expectEqual(snan_u32, @as(u32, @bitCast(snan(f32))));
    try expectEqual(snan_u64, @as(u64, @bitCast(snan(f64))));
    try expectEqual(snan_u80, @as(u80, @bitCast(snan(f80))));
    try expectEqual(snan_u128, @as(u128, @bitCast(snan(f128))));
}

std.math.float.std

别名

第 1 行

别名目标 std

源码

std/math/float.zig

const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;

/// 用于处理精度高于双精度的浮点类型
/// (`f80`、`f128`、`c_longdouble`)的函数命名空间。
/// 在 C 中通常称为 `long double`。
pub const long_double = struct {
    const U80 = @Int(.unsigned, 80);

    inline fn bitWidth(x: anytype) u16 {
        const T = @TypeOf(x);
        return switch (T) {
            f80, f128, c_longdouble => @typeInfo(T).float.bits,
            else => @compileError("Unsupported type: " ++ @typeName(T) ++ "\nPass a `f80`, `f128`, or `c_longdouble`."),
        };
    }

    /// 返回 `long double` 的符号位和指数位。
    pub fn signExponent(x: anytype) u16 {
        const bit_width = bitWidth(x);
        switch (bit_width) {
            80 => {
                const bits: U80 = @bitCast(x);
                return @intCast(bits >> 64);
            },
            128 => {
                const bits: u128 = @bitCast(x);
                return @intCast(bits >> 112);
            },
            // 某些目标的 `c_longdouble` 可能少于 80 位;我们希望对此报错
            else => @compileError(std.fmt.comptimePrint("`signExponent` supports floats of only `80` and `128` bit width, got bit width: {d}", .{bit_width})),
        }
    }

    test "signExponent" {
        try expectEqual(signExponent(@as(f80, -0.0)), 0x8000);
        try expectEqual(signExponent(@as(f128, 0.0)), 0x0000);
        try expectEqual(signExponent(@as(f128, 42.0)), 0x4004);
        try expectEqual(signExponent(nan(c_longdouble)), 0x7FFF);
    }

    /// 取 `long double` 尾数的最高 16 位。
    pub fn mantissaTop(x: anytype) u16 {
        const bit_width = bitWidth(x);
        switch (bit_width) {
            80 => {
                const bits: U80 = @bitCast(x);
                return @intCast((bits >> 48) & 0xFFFF);
            },
            128 => {
                const bits: u128 = @bitCast(x);
                return @intCast((bits >> 96) & 0xFFFF);
            },
            // 某些目标的 `c_longdouble` 可能少于 80 位;我们希望对此报错
            else => @compileError(std.fmt.comptimePrint("`mantissaTop` supports floats of only `80` and `128` bit width, got bit width: {d}", .{bit_width})),
        }
    }

    test "mantissaTop" {
        try expectEqual(mantissaTop(@as(f80, -0.0)), 0x0000);
        try expectEqual(mantissaTop(nan(f128)), 0x8000);
        try expectEqual(mantissaTop(@as(f128, 42.0)), 0x5000);
    }
};

pub fn FloatRepr(comptime Float: type) type {
    const fractional_bits = floatFractionalBits(Float);
    const exponent_bits = floatExponentBits(Float);
    return packed struct {
        const Repr = @This();

        mantissa: StoredMantissa,
        exponent: BiasedExponent,
        sign: std.math.Sign,

        pub const StoredMantissa = @Int(.unsigned, floatMantissaBits(Float));
        pub const Mantissa = @Int(.unsigned, 1 + fractional_bits);
        pub const Exponent = @Int(.signed, exponent_bits);
        pub const BiasedExponent = enum(@Int(.unsigned, exponent_bits)) {
            denormal = 0,
            min_normal = 1,
            zero = (1 << (exponent_bits - 1)) - 1,
            max_normal = (1 << exponent_bits) - 2,
            infinite = (1 << exponent_bits) - 1,
            _,

            pub const Int = @typeInfo(BiasedExponent).@"enum".tag_type;

            pub fn unbias(biased: BiasedExponent) Exponent {
                switch (biased) {
                    .denormal => unreachable,
                    else => return @bitCast(@backingInt(biased) -% @backingInt(BiasedExponent.zero)),
                    .infinite => unreachable,
                }
            }

            pub fn bias(unbiased: Exponent) BiasedExponent {
                return @fromBackingInt(@intCast(@backingInt(BiasedExponent.zero) +% @as(Int, @bitCast(unbiased))));
            }
        };

        pub const Normalized = struct {
            fraction: Fraction,
            exponent: Normalized.Exponent,

            pub const Fraction = @Int(.unsigned, fractional_bits);
            pub const Exponent = @Int(.signed, 1 + exponent_bits);

            /// 此实现目前截断非正规值;在可用于生成舍入值之前,需要先修复该问题。
            ///
            pub fn reconstruct(normalized: Normalized, sign: std.math.Sign) Float {
                if (normalized.exponent > comptime BiasedExponent.max_normal.unbias()) return @bitCast(Repr{
                    .mantissa = 0,
                    .exponent = .infinite,
                    .sign = sign,
                });
                const mantissa = @as(Mantissa, 1 << fractional_bits) | normalized.fraction;
                if (normalized.exponent < comptime BiasedExponent.min_normal.unbias()) return @bitCast(Repr{
                    .mantissa = @truncate(std.math.shr(
                        Mantissa,
                        mantissa,
                        (comptime BiasedExponent.min_normal.unbias()) - normalized.exponent,
                    )),
                    .exponent = .denormal,
                    .sign = sign,
                });
                return @bitCast(Repr{
                    .mantissa = @truncate(mantissa),
                    .exponent = .bias(@intCast(normalized.exponent)),
                    .sign = sign,
                });
            }
        };

        pub const Classified = union(enum) { normalized: Normalized, infinity, nan, invalid };
        fn classify(repr: Repr) Classified {
            return switch (repr.exponent) {
                .denormal => {
                    const mantissa: Mantissa = repr.mantissa;
                    const shift = @clz(mantissa);
                    return .{ .normalized = .{
                        .fraction = @truncate(mantissa << shift),
                        .exponent = @as(Normalized.Exponent, comptime BiasedExponent.min_normal.unbias()) - shift,
                    } };
                },
                else => if (repr.mantissa <= std.math.maxInt(Normalized.Fraction)) .{ .normalized = .{
                    .fraction = @intCast(repr.mantissa),
                    .exponent = repr.exponent.unbias(),
                } } else .invalid,
                .infinite => switch (repr.mantissa) {
                    0 => .infinity,
                    else => .nan,
                },
            };
        }
    };
}

/// 为浮点类型 T 创建原始的 "1.0" 尾数,用于消除重复的 f80 逻辑。
inline fn mantissaOne(comptime T: type) comptime_int {
    return if (@typeInfo(T).float.bits == 80) 1 << floatFractionalBits(T) else 0;
}

/// 根据无偏指数和原始尾数创建浮点类型 T 的值。
inline fn reconstructFloat(comptime T: type, comptime exponent: comptime_int, comptime mantissa: comptime_int) T {
    const TBits = @Int(.unsigned, @bitSizeOf(T));
    const biased_exponent = @as(TBits, exponent + floatExponentMax(T));
    return @as(T, @bitCast((biased_exponent << floatMantissaBits(T)) | @as(TBits, mantissa)));
}

/// 返回浮点类型 T 的指数位数。
pub inline fn floatExponentBits(comptime T: type) comptime_int {
    comptime assert(@typeInfo(T) == .float);

    return switch (@typeInfo(T).float.bits) {
        16 => 5,
        32 => 8,
        64 => 11,
        80 => 15,
        128 => 15,
        else => @compileError("unknown floating point type " ++ @typeName(T)),
    };
}

/// 返回浮点类型 T 的尾数位数。
pub inline fn floatMantissaBits(comptime T: type) comptime_int {
    comptime assert(@typeInfo(T) == .float);

    return switch (@typeInfo(T).float.bits) {
        16 => 10,
        32 => 23,
        64 => 52,
        80 => 64,
        128 => 112,
        else => @compileError("unknown floating point type " ++ @typeName(T)),
    };
}

/// 返回浮点类型 T 尾数中的小数位数。
pub inline fn floatFractionalBits(comptime T: type) comptime_int {
    comptime assert(@typeInfo(T) == .float);

    // 标准 IEEE 浮点数的整数部分隐含为 0.m 或 1.m。
    // f80 是特例,最高有效位中显式存储了这一位。
    // 此函数对应 C 中的 `MANT_DIG - 1'。
    return switch (@typeInfo(T).float.bits) {
        16 => 10,
        32 => 23,
        64 => 52,
        80 => 63,
        128 => 112,
        else => @compileError("unknown floating point type " ++ @typeName(T)),
    };
}

/// 返回浮点类型 T 可表示
/// 正规值的最小指数。
pub inline fn floatExponentMin(comptime T: type) comptime_int {
    return -floatExponentMax(T) + 1;
}

/// 返回浮点类型 T 中可以表示
/// 正规值的最大指数。
pub inline fn floatExponentMax(comptime T: type) comptime_int {
    return (1 << (floatExponentBits(T) - 1)) - 1;
}

/// 返回浮点类型 T 可表示的最小非正规数。
pub inline fn floatTrueMin(comptime T: type) T {
    return reconstructFloat(T, floatExponentMin(T) - 1, 1);
}

/// 返回浮点类型 T 可表示的最小正规数。
pub inline fn floatMin(comptime T: type) T {
    return reconstructFloat(T, floatExponentMin(T), mantissaOne(T));
}

/// 返回浮点类型 T 可表示的最大正规数。
pub inline fn floatMax(comptime T: type) T {
    const all1s_mantissa = (1 << floatMantissaBits(T)) - 1;
    return reconstructFloat(T, floatExponentMax(T), all1s_mantissa);
}

/// 返回浮点类型 T 的机器 epsilon。
pub inline fn floatEps(comptime T: type) T {
    return reconstructFloat(T, -floatFractionalBits(T), mantissaOne(T));
}

/// 返回浮点类型 T 的局部 epsilon。
pub inline fn floatEpsAt(comptime T: type, x: T) T {
    switch (@typeInfo(T)) {
        .float => |F| {
            const U: type = @Int(.unsigned, F.bits);
            const u: U = @bitCast(x);
            const y: T = @bitCast(u ^ 1);
            return @abs(x - y);
        },
        else => @compileError("floatEpsAt only supports floats"),
    }
}

/// 返回浮点 `Type` 的无穷值。
pub inline fn inf(comptime Type: type) Type {
    const RuntimeType = switch (Type) {
        else => Type,
        comptime_float => f128, // 任意浮点类型均可
    };
    return reconstructFloat(RuntimeType, floatExponentMax(RuntimeType) + 1, mantissaOne(RuntimeType));
}

/// 返回浮点 `Type` 的规范静默 NaN 表示。
pub inline fn nan(comptime Type: type) Type {
    const RuntimeType = switch (Type) {
        else => Type,
        comptime_float => f128, // 任意浮点类型均可
    };
    return reconstructFloat(
        RuntimeType,
        floatExponentMax(RuntimeType) + 1,
        mantissaOne(RuntimeType) | 1 << (floatFractionalBits(RuntimeType) - 1),
    );
}

/// 返回浮点 `Type` 的信号 NaN 表示。
///
/// TODO: 已知 LLVM 在某些架构上会将其错误编译为静默 NaN;
///       跟踪问题:https://github.com/ziglang/zig/issues/14366
pub inline fn snan(comptime Type: type) Type {
    const RuntimeType = switch (Type) {
        else => Type,
        comptime_float => f128, // 任意浮点类型均可
    };
    return reconstructFloat(
        RuntimeType,
        floatExponentMax(RuntimeType) + 1,
        mantissaOne(RuntimeType) | 1 << (floatFractionalBits(RuntimeType) - 2),
    );
}

fn floatBits(comptime Type: type) !void {
    // 为符号位额外加 1,因为它独立于其他位
    const size = 1 + floatExponentBits(Type) + floatMantissaBits(Type);
    try expect(@bitSizeOf(Type) == size);
    try expect(floatFractionalBits(Type) <= floatMantissaBits(Type));

    // 对于机器 epsilon,断言 expmin <= -prec <= expmax。
    try expect(floatExponentMin(Type) <= -floatFractionalBits(Type));
    try expect(-floatFractionalBits(Type) <= floatExponentMax(Type));
}
test floatBits {
    try floatBits(f16);
    try floatBits(f32);
    try floatBits(f64);
    try floatBits(f80);
    try floatBits(f128);
    try floatBits(c_longdouble);
}

test inf {
    const inf_u16: u16 = 0x7C00;
    const inf_u32: u32 = 0x7F800000;
    const inf_u64: u64 = 0x7FF0000000000000;
    const inf_u80: u80 = 0x7FFF8000000000000000;
    const inf_u128: u128 = 0x7FFF0000000000000000000000000000;
    try expectEqual(inf_u16, @as(u16, @bitCast(inf(f16))));
    try expectEqual(inf_u32, @as(u32, @bitCast(inf(f32))));
    try expectEqual(inf_u64, @as(u64, @bitCast(inf(f64))));
    try expectEqual(inf_u80, @as(u80, @bitCast(inf(f80))));
    try expectEqual(inf_u128, @as(u128, @bitCast(inf(f128))));
}

test nan {
    const qnan_u16: u16 = 0x7E00;
    const qnan_u32: u32 = 0x7FC00000;
    const qnan_u64: u64 = 0x7FF8000000000000;
    const qnan_u80: u80 = 0x7FFFC000000000000000;
    const qnan_u128: u128 = 0x7FFF8000000000000000000000000000;
    try expectEqual(qnan_u16, @as(u16, @bitCast(nan(f16))));
    try expectEqual(qnan_u32, @as(u32, @bitCast(nan(f32))));
    try expectEqual(qnan_u64, @as(u64, @bitCast(nan(f64))));
    try expectEqual(qnan_u80, @as(u80, @bitCast(nan(f80))));
    try expectEqual(qnan_u128, @as(u128, @bitCast(nan(f128))));
}

test snan {
    const snan_u16: u16 = 0x7D00;
    const snan_u32: u32 = 0x7FA00000;
    const snan_u64: u64 = 0x7FF4000000000000;
    const snan_u80: u80 = 0x7FFFA000000000000000;
    const snan_u128: u128 = 0x7FFF4000000000000000000000000000;
    try expectEqual(snan_u16, @as(u16, @bitCast(snan(f16))));
    try expectEqual(snan_u32, @as(u32, @bitCast(snan(f32))));
    try expectEqual(snan_u64, @as(u64, @bitCast(snan(f64))));
    try expectEqual(snan_u80, @as(u80, @bitCast(snan(f80))));
    try expectEqual(snan_u128, @as(u128, @bitCast(snan(f128))));
}