builtinstdfloatassertmemtestingAlignmentepiphitaulog2elog10eln2ln10two_sqrtpisqrt2sqrt1_2rad_per_degdeg_per_radSignFloatReprfloatExponentBitsfloatMantissaBitsfloatFractionalBitsfloatExponentMinfloatExponentMaxfloatTrueMinfloatMinfloatMaxfloatEpsfloatEpsAtinflong_doublenansnanapproxEqAbsapproxEqRelraiseInvalidraiseUnderflowraiseOverflowraiseInexactraiseDivByZeroisNanisSignalNanfrexpFrexpmodfModfcopysignisFiniteisInfisPositiveInfisNegativeInfisPositiveZeroisNegativeZeroisNormalnextAftersignbitscalbnldexppowpowisqrtcbrtacosasinatanatan2hypotexpm1ilogbloglog2log10log10_intlog_intlog1pasinhacoshatanhsinhcoshtanhgcdlcmgammalgammasincostanradiansToDegreesdegreesToRadiansexpexp2complexComplexbigMinwrapclampmuladdsubnegateshlExactshlshrrotrrotlLog2IntLog2IntCeilIntFittingRangetestOverflowdivTrunctestDivTruncdivFloortestDivFloordivCeiltestDivCeildivExacttestDivExactmodtestModremtestRemnegateCastcastAlignCastErrorAlignCastResultalignCastisPowerOfTwoByteAlignedIntroundtruncfloorfloorPowerOfTwotestFloorPowerOfTwoceilceilPowerOfTwoPromoteceilPowerOfTwoceilPowerOfTwoAsserttestCeilPowerOfTwoPromotetestCeilPowerOfTwolog2_intlog2_int_ceillossyCastlerpmaxIntminIntmulWideOrderorderCompareOperatorcompareboolMaskrunTestcomptimeModF80SignOfsigntestSignsignExtend
std.math.acos
别名
别名目标 std.math.acos.acos
std.math.acosh
别名
别名目标 std.math.acosh.acosh
std.math.add
函数
返回 a 与 b 的和。溢出时返回错误。
pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T)
参数
T: type
a: T
b: T
std.math.alignCast
函数
对指针进行对齐转换,但对齐不正确时返回错误。
pub fn alignCast(comptime alignment: Alignment, ptr: anytype) AlignCastError!AlignCastResult(alignment, @TypeOf(ptr))
参数
alignment: Alignment
错误
- UnalignedMemory
std.math.AlignCastError
错误集合
错误
- UnalignedMemory
std.math.AlignCastResult
类型函数
fn AlignCastResult(comptime alignment: Alignment, comptime Ptr: type) type
参数
alignment: Alignment
Ptr: type
std.math.Alignment
别名
别名目标 std.mem.Alignment
std.math.approxEqAbs
函数
近似比较两个浮点值 x 和 y。
如果二者的绝对差小于或等于
指定容差,则返回 true。
tolerance 参数是判断两个数是否足够
接近时使用的绝对容差;较好的取值为
floatEps(T) 的一个较小倍数。
注意,建议使用此函数比较零附近的
较小数;其他情况下建议使用 approxEqRel。
NaN 值绝不会被视为与任何值相等。
pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool
参数
T: type
x: T
y: T
tolerance: T
用法示例
test approxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value));
try testing.expect(!approxEqAbs(T, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, 1.0 + 1 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2));
try testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2));
}
comptime {
// `comptime_float` 保证具有其他最大浮点类型,即 f128 的
// 精度和运算,但它没有
// 定义明确的布局,因此不能像上方测试那样,依靠 `@bitCast`
// 构造最小的 epsilon 值。同样,
// 也无法表示最大/最小值、`NaN` 或 `Inf`。
const eps_value = 1e-4;
try testing.expect(approxEqAbs(comptime_float, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 0.0, -0.0, eps_value));
try testing.expect(!approxEqAbs(comptime_float, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 1.0 + 1 * eps_value, 1.0, eps_value));
}
}
std.math.approxEqRel
函数
对两个浮点值 x 和 y 进行近似比较。
若它们的绝对差小于或等于
max(|x|, |y|) * tolerance,则返回 true,其中 tolerance 是
大于零的正数。
tolerance 参数是判断两个数是否足够接近时使用的
相对容差;此参数通常可取
sqrt(floatEps(T)),意为至少一半数位相同时,
便将两个数视为相等。
注意:比较接近零的小数值时,此函数
不会给出有意义的结果,应改用 approxEqAbs。
NaN 与任何值都不被视为相等。
pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool
参数
T: type
x: T
y: T
tolerance: T
用法示例
test approxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const sqrt_eps_value = comptime sqrt(eps_value);
const nan_value = comptime nan(T);
const inf_value = comptime inf(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value));
try testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value));
}
comptime {
// `comptime_float` 保证具有其他最大浮点类型,即 f128 的
// 精度和运算,但它没有
// 定义明确的布局,因此不能像上方测试那样,依靠 `@bitCast`
// 构造最小的 epsilon 值。同样,
// 也无法表示最大/最小值、`NaN` 或 `Inf`。
const eps_value = 1e-4;
const sqrt_eps_value = sqrt(eps_value);
try testing.expect(approxEqRel(comptime_float, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(comptime_float, 1.0, 0.0, sqrt_eps_value));
}
}
std.math.asin
别名
别名目标 std.math.asin.asin
std.math.asinh
别名
别名目标 std.math.asinh.asinh
std.math.assert
别名
别名目标 std.debug.assert
std.math.atan
别名
别名目标 std.math.atan.atan
std.math.atan2
别名
别名目标 std.math.atan2.atan2
std.math.atanh
别名
别名目标 std.math.atanh.atanh
std.math.big
别名
别名目标 std.math.big
std.math.boolMask
函数
值为 true 时返回全一掩码,为 false 时返回全零掩码。 对于寄存器大小的整数,会编译为一条指令。
pub inline fn boolMask(comptime MaskInt: type, value: bool) MaskInt
参数
MaskInt: type
value: bool
用法示例
test boolMask {
const runTest = struct {
fn runTest() !void {
try testing.expectEqual(@as(u1, 0), boolMask(u1, false));
try testing.expectEqual(@as(u1, 1), boolMask(u1, true));
try testing.expectEqual(@as(i1, 0), boolMask(i1, false));
try testing.expectEqual(@as(i1, -1), boolMask(i1, true));
try testing.expectEqual(@as(u13, 0), boolMask(u13, false));
try testing.expectEqual(@as(u13, 0x1FFF), boolMask(u13, true));
try testing.expectEqual(@as(i13, 0), boolMask(i13, false));
try testing.expectEqual(@as(i13, -1), boolMask(i13, true));
try testing.expectEqual(@as(u32, 0), boolMask(u32, false));
try testing.expectEqual(@as(u32, 0xFFFF_FFFF), boolMask(u32, true));
try testing.expectEqual(@as(i32, 0), boolMask(i32, false));
try testing.expectEqual(@as(i32, -1), boolMask(i32, true));
}
}.runTest;
try runTest();
try comptime runTest();
}
std.math.builtin
常量
std.math.ByteAlignedInt
类型函数
将给定整数类型的位宽对齐到可被 8 整除的位宽。
pub fn ByteAlignedInt(comptime T: type) type
参数
T: type
用法示例
test ByteAlignedInt {
try testing.expect(ByteAlignedInt(u0) == u0);
try testing.expect(ByteAlignedInt(u3) == u8);
try testing.expect(ByteAlignedInt(u8) == u8);
try testing.expect(ByteAlignedInt(i111) == i112);
try testing.expect(ByteAlignedInt(u129) == u136);
}
std.math.cast
函数
将整数转换为另一整数类型。 若值无法表示,则返回 null。
pub fn cast(comptime T: type, x: anytype) ?T
参数
T: type
用法示例
test cast {
try testing.expect(cast(u8, 300) == null);
try testing.expect(cast(u8, @as(u32, 300)) == null);
try testing.expect(cast(i8, -200) == null);
try testing.expect(cast(i8, @as(i32, -200)) == null);
try testing.expect(cast(u8, -1) == null);
try testing.expect(cast(u8, @as(i8, -1)) == null);
try testing.expect(cast(u64, -1) == null);
try testing.expect(cast(u64, @as(i8, -1)) == null);
try testing.expect(cast(u8, 255).? == @as(u8, 255));
try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255));
try testing.expect(@TypeOf(cast(u8, 255).?) == u8);
try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8);
}
std.math.cbrt
别名
别名目标 std.math.cbrt.cbrt
std.math.ceil
函数
返回不小于给定浮点数的最小整数值。 若存在专用硬件指令,则使用该指令。 等价于调用内置函数 @ceil。
pub inline fn ceil(value: anytype) @TypeOf(value)
std.math.ceilPowerOfTwo
函数
返回下一个 2 的幂;若值已是 2 的幂,则返回原值。 仅能使用无符号整数。不允许输入零。 若结果无法表示,则返回错误。
pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T)
参数
T: type
value: T
用法示例
test ceilPowerOfTwo {
try testCeilPowerOfTwo();
try comptime testCeilPowerOfTwo();
}
std.math.ceilPowerOfTwoAssert
函数
返回下一个 2 的幂(若该值已是 2 的幂,则原样返回)。 仅可使用无符号整数。不允许输入零。 断言结果能放入该类型。
pub fn ceilPowerOfTwoAssert(comptime T: type, value: T) T
参数
T: type
value: T
std.math.ceilPowerOfTwoPromote
函数
返回下一个二的幂;若值本身已是二的幂,则保持不变。 仅可使用无符号整数。不允许输入零。 结果类型比输入类型多 1 位。
pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) @Int(@typeInfo(T).int.signedness, @typeInfo(T).int.bits + 1)
参数
T: type
value: T
用法示例
test ceilPowerOfTwoPromote {
try testCeilPowerOfTwoPromote();
try comptime testCeilPowerOfTwoPromote();
}
std.math.clamp
函数
奇对称斜坡函数。
| _____
| /
|/
-------/-------
/|
_____/ |
|
将 val 限制在闭区间 [lower, upper] 内。
pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper)
用法示例
test clamp {
// 位于范围内
try testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1);
// 下方
try testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4);
// 上方
try testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
// 浮点数
try testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
try testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
// 向量
try testing.expect(@reduce(.And, std.math.clamp(@as(@Vector(3, f32), .{ 1.4, 15.23, 28.3 }), @as(@Vector(3, f32), .{ 9.8, 13.2, 15.6 }), @as(@Vector(3, f32), .{ 15.2, 22.8, 26.3 })) == @as(@Vector(3, f32), .{ 9.8, 15.23, 26.3 })));
// 编译期与非编译期内容混合
var i: i32 = 1;
_ = &i;
try testing.expect(std.math.clamp(i, 0, 1) == 1);
}
std.math.compare
函数
此函数与比较运算符执行相同操作,但运算符 是运行时已知的枚举值。适用于支持 比较运算符的任意操作数。
pub fn compare(a: anytype, op: CompareOperator, b: anytype) bool
参数
op: CompareOperator
用法示例
test compare {
try testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255)));
try testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1)));
try testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255)));
try testing.expect(compare(@as(u8, 255), .gt, @as(i8, -1)));
try testing.expect(!compare(@as(u8, 255), .lte, @as(i8, -1)));
try testing.expect(compare(@as(i8, -1), .lt, @as(u9, 255)));
try testing.expect(!compare(@as(i8, -1), .gte, @as(u9, 255)));
try testing.expect(compare(@as(u9, 255), .gt, @as(i8, -1)));
try testing.expect(!compare(@as(u9, 255), .lte, @as(i8, -1)));
try testing.expect(compare(@as(i9, -1), .lt, @as(u8, 255)));
try testing.expect(!compare(@as(i9, -1), .gte, @as(u8, 255)));
try testing.expect(compare(@as(u8, 255), .gt, @as(i9, -1)));
try testing.expect(!compare(@as(u8, 255), .lte, @as(i9, -1)));
try testing.expect(compare(@as(u8, 1), .lt, @as(u8, 2)));
try testing.expect(@as(u8, @bitCast(@as(i8, -1))) == @as(u8, 255));
try testing.expect(!compare(@as(u8, 255), .eq, @as(i8, -1)));
try testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1)));
}
std.math.CompareOperator
容器
另请参见 Order。
字段
lt小于(<)
lte小于或等于(<=)
eq等于(==)
gte大于或等于(>=)
gt大于(>)
neq不相等(!=)
std.math.CompareOperator.reverse
函数
反转比较方向。 交换左右操作数时使用。
pub fn reverse(op: CompareOperator) CompareOperator
参数
op: CompareOperator
用法示例
test reverse {
inline for (@typeInfo(CompareOperator).@"enum".field_values) |op_field_value| {
const op = @as(CompareOperator, @fromBackingInt(@intCast(op_field_value)));
try testing.expect(compare(2, op, 3) == compare(3, op.reverse(), 2));
try testing.expect(compare(3, op, 3) == compare(3, op.reverse(), 3));
try testing.expect(compare(4, op, 3) == compare(3, op.reverse(), 4));
}
}
std.math.complex
别名
别名目标 std.math.complex
std.math.Complex
别名
std.math.comptimeMod
函数
使用最小整数类型返回 num 的模
pub fn comptimeMod(num: anytype, comptime denom: comptime_int) IntFittingRange(0, denom - 1)
参数
denom: comptime_int
std.math.copysign
别名
std.math.cos
函数
浮点数的三角余弦函数。 若可用,则使用专用硬件指令。 等同于调用内置函数 @cos
pub inline fn cos(value: anytype) @TypeOf(value)
std.math.cosh
别名
别名目标 std.math.cosh.cosh
std.math.deg_per_rad
常量
180.0/pi
std.math.degreesToRadians
函数
将角度从度转换为弧度。T 必须为浮点数、编译期数值或浮点向量。
pub fn degreesToRadians(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang)
用法示例
test degreesToRadians {
const ninety: f32 = 90;
const neg_two_seventy: f32 = -270;
const three_sixty: f32 = 360;
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(ninety), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(neg_two_seventy), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(three_sixty), 1e-6);
const result = degreesToRadians(@Vector(3, f32){
ninety,
neg_two_seventy,
three_sixty,
});
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), result[0], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), result[1], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), result[2], 1e-6);
}
std.math.divCeil
函数
计算 numerator 除以 denominator,向正无穷舍入。 溢出或 denominator 为零时返回错误。
pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T
参数
T: type
numerator: T
denominator: T
用法示例
test divCeil {
try testDivCeil();
try comptime testDivCeil();
}
std.math.divExact
函数
计算 numerator 除以 denominator。 商不是整数、denominator 为零或发生溢出时返回错误。
pub fn divExact(comptime T: type, numerator: T, denominator: T) !T
参数
T: type
numerator: T
denominator: T
用法示例
test divExact {
try testDivExact();
try comptime testDivExact();
}
std.math.divFloor
函数
计算分子除以分母的商,向负 无穷取整。溢出或分母为 零时返回错误。
pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T
参数
T: type
numerator: T
denominator: T
用法示例
test divFloor {
try testDivFloor();
try comptime testDivFloor();
}
std.math.divTrunc
函数
计算分子除以分母的商,向零取整。溢出或 分母为零时返回错误。
pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T
参数
T: type
numerator: T
denominator: T
用法示例
test divTrunc {
try testDivTrunc();
try comptime testDivTrunc();
}
std.math.e
常量
欧拉数(e)
std.math.exp
函数
计算浮点数的以 e 为底的指数函数。 若可用,则使用专用硬件指令。 等同于调用内置函数 @exp。
pub inline fn exp(value: anytype) @TypeOf(value)
std.math.exp2
函数
计算浮点数的以 2 为底的指数函数。 若可用,则使用专用硬件指令。 等同于调用内置函数 @exp2。
pub inline fn exp2(value: anytype) @TypeOf(value)
std.math.expm1
别名
别名目标 std.math.expm1.expm1
std.math.F80
容器
字段
fraction: u64
exp: u16
std.math.F80.fromFloat
函数
pub fn fromFloat(x: f80) F80
参数
x: f80
std.math.F80.toFloat
函数
pub fn toFloat(self: F80) f80
参数
self: F80
std.math.float
别名
别名目标 std.math.float
std.math.floatEps
别名
std.math.floatEpsAt
别名
std.math.floatExponentBits
别名
std.math.floatExponentMax
别名
std.math.floatExponentMin
别名
std.math.floatFractionalBits
别名
std.math.floatMantissaBits
别名
std.math.floatMax
别名
std.math.floatMin
别名
std.math.FloatRepr
别名
std.math.floatTrueMin
别名
std.math.floor
函数
返回不大于给定浮点数的最大整数值。 若可用,则使用专门的硬件指令。 与调用内置函数 @floor 相同。
pub inline fn floor(value: anytype) @TypeOf(value)
std.math.floorPowerOfTwo
函数
返回小于或等于给定值的最大 2 的幂; 如果给定值小于或等于零,则返回零。
pub fn floorPowerOfTwo(comptime T: type, value: T) T
参数
T: type
value: T
用法示例
test floorPowerOfTwo {
try testFloorPowerOfTwo();
try comptime testFloorPowerOfTwo();
}
std.math.frexp
别名
别名目标 std.math.frexp.frexp
std.math.Frexp
别名
别名目标 std.math.frexp.Frexp
std.math.gamma
别名
别名目标 std.math.gamma.gamma
std.math.gcd
别名
别名目标 std.math.gcd.gcd
std.math.hypot
别名
别名目标 std.math.hypot.hypot
std.math.ilogb
别名
别名目标 std.math.ilogb.ilogb
std.math.inf
别名
别名目标 std.math.float.inf
std.math.IntFittingRange
类型函数
返回能同时容纳 from 和 to 的最小整数类型。
pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type
参数
from: comptime_int
to: comptime_int
用法示例
test IntFittingRange {
try testing.expect(IntFittingRange(0, 0) == u0);
try testing.expect(IntFittingRange(0, 1) == u1);
try testing.expect(IntFittingRange(0, 2) == u2);
try testing.expect(IntFittingRange(0, 3) == u2);
try testing.expect(IntFittingRange(0, 4) == u3);
try testing.expect(IntFittingRange(0, 7) == u3);
try testing.expect(IntFittingRange(0, 8) == u4);
try testing.expect(IntFittingRange(0, 9) == u4);
try testing.expect(IntFittingRange(0, 15) == u4);
try testing.expect(IntFittingRange(0, 16) == u5);
try testing.expect(IntFittingRange(0, 17) == u5);
try testing.expect(IntFittingRange(0, 4095) == u12);
try testing.expect(IntFittingRange(2000, 4095) == u12);
try testing.expect(IntFittingRange(0, 4096) == u13);
try testing.expect(IntFittingRange(2000, 4096) == u13);
try testing.expect(IntFittingRange(0, 4097) == u13);
try testing.expect(IntFittingRange(2000, 4097) == u13);
try testing.expect(IntFittingRange(0, 123456789123456798123456789) == u87);
try testing.expect(IntFittingRange(0, 123456789123456798123456789123456789123456798123456789) == u177);
try testing.expect(IntFittingRange(-1, -1) == i1);
try testing.expect(IntFittingRange(-1, 0) == i1);
try testing.expect(IntFittingRange(-1, 1) == i2);
try testing.expect(IntFittingRange(-2, -2) == i2);
try testing.expect(IntFittingRange(-2, -1) == i2);
try testing.expect(IntFittingRange(-2, 0) == i2);
try testing.expect(IntFittingRange(-2, 1) == i2);
try testing.expect(IntFittingRange(-2, 2) == i3);
try testing.expect(IntFittingRange(-1, 2) == i3);
try testing.expect(IntFittingRange(-1, 3) == i3);
try testing.expect(IntFittingRange(-1, 4) == i4);
try testing.expect(IntFittingRange(-1, 7) == i4);
try testing.expect(IntFittingRange(-1, 8) == i5);
try testing.expect(IntFittingRange(-1, 9) == i5);
try testing.expect(IntFittingRange(-1, 15) == i5);
try testing.expect(IntFittingRange(-1, 16) == i6);
try testing.expect(IntFittingRange(-1, 17) == i6);
try testing.expect(IntFittingRange(-1, 4095) == i13);
try testing.expect(IntFittingRange(-4096, 4095) == i13);
try testing.expect(IntFittingRange(-1, 4096) == i14);
try testing.expect(IntFittingRange(-4097, 4095) == i14);
try testing.expect(IntFittingRange(-1, 4097) == i14);
try testing.expect(IntFittingRange(-1, 123456789123456798123456789) == i88);
try testing.expect(IntFittingRange(-1, 123456789123456798123456789123456789123456798123456789) == i178);
}
std.math.isFinite
别名
std.math.isInf
别名
别名目标 std.math.isinf.isInf
std.math.isNan
别名
别名目标 std.math.isnan.isNan
std.math.isNegativeInf
别名
std.math.isNegativeZero
别名
std.math.isNormal
别名
std.math.isPositiveInf
别名
std.math.isPositiveZero
别名
std.math.isPowerOfTwo
函数
断言 int > 0。
pub fn isPowerOfTwo(int: anytype) bool
用法示例
test isPowerOfTwo {
try testing.expect(isPowerOfTwo(@as(u8, 1)));
try testing.expect(isPowerOfTwo(2));
try testing.expect(!isPowerOfTwo(@as(i16, 3)));
try testing.expect(isPowerOfTwo(4));
try testing.expect(!isPowerOfTwo(@as(u32, 31)));
try testing.expect(isPowerOfTwo(32));
try testing.expect(!isPowerOfTwo(@as(i64, 63)));
try testing.expect(isPowerOfTwo(128));
try testing.expect(isPowerOfTwo(@as(u128, 256)));
}
std.math.isSignalNan
别名
std.math.lcm
别名
别名目标 std.math.lcm.lcm
std.math.ldexp
别名
别名目标 std.math.ldexp.ldexp
std.math.lerp
函数
根据 t 在 a 与 b 之间进行线性插值。 t 的范围通常为 0.0 到 1.0,但也可能超出此范围。 支持浮点数和浮点数向量。
由于浮点误差,t 为 1 时不保证返回 b。 此函数具有单调性。
pub fn lerp(a: anytype, b: anytype, t: anytype) @TypeOf(a, b, t)
用法示例
test lerp {
if (builtin.zig_backend == .stage2_c and builtin.cpu.arch.isArm()) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_c and builtin.cpu.arch.isX86()) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_x86_64 and !comptime builtin.cpu.has(.x86, .fma)) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/17884
try testing.expectEqual(@as(f64, 75), lerp(50, 100, 0.5));
try testing.expectEqual(@as(f32, 43.75), lerp(50, 25, 0.25));
try testing.expectEqual(@as(f64, -31.25), lerp(-50, 25, 0.25));
try testing.expectEqual(@as(f64, 30), lerp(10, 20, 2.0));
try testing.expectEqual(@as(f64, 5), lerp(10, 20, -0.5));
try testing.expectApproxEqRel(@as(f32, -7.16067345e+03), lerp(-10000.12345, -5000.12345, 0.56789), 1e-19);
try testing.expectApproxEqRel(@as(f64, 7.010987590521e+62), lerp(0.123456789e-64, 0.123456789e64, 0.56789), 1e-33);
try testing.expectEqual(@as(f32, 0.0), lerp(@as(f32, 1.0e8), 1.0, 1.0));
try testing.expectEqual(@as(f64, 0.0), lerp(@as(f64, 1.0e16), 1.0, 1.0));
try testing.expectEqual(@as(f32, 1.0), lerp(@as(f32, 1.0e7), 1.0, 1.0));
try testing.expectEqual(@as(f64, 1.0), lerp(@as(f64, 1.0e15), 1.0, 1.0));
{
const a: @Vector(3, f32) = @splat(0);
const b: @Vector(3, f32) = @splat(50);
const t: @Vector(3, f32) = @splat(0.5);
try testing.expectEqual(
@Vector(3, f32){ 25, 25, 25 },
lerp(a, b, t),
);
}
{
const a: @Vector(3, f64) = @splat(50);
const b: @Vector(3, f64) = @splat(100);
const t: @Vector(3, f64) = @splat(0.5);
try testing.expectEqual(
@Vector(3, f64){ 75, 75, 75 },
lerp(a, b, t),
);
}
{
const a: @Vector(2, f32) = @splat(40);
const b: @Vector(2, f32) = @splat(80);
const t: @Vector(2, f32) = @Vector(2, f32){ 0.25, 0.75 };
try testing.expectEqual(
@Vector(2, f32){ 50, 70 },
lerp(a, b, t),
);
}
}
std.math.lgamma
别名
std.math.ln10
常量
ln(10)
std.math.ln2
常量
ln(2)
std.math.log
别名
别名目标 std.math.log.log
std.math.log_int
别名
std.math.log10
别名
别名目标 std.math.log10.log10
std.math.log10_int
别名
std.math.log10e
常量
log10(e)
std.math.log1p
别名
别名目标 std.math.log1p.log1p
std.math.log2
别名
别名目标 std.math.log2.log2
std.math.log2_int
函数
返回整数值 x 以 2 为底的对数, 向下舍入到最近整数。
pub fn log2_int(comptime T: type, x: T) Log2Int(T)
参数
T: type
x: T
用法示例
test log2_int {
try testing.expect(log2_int(u32, 1) == 0);
try testing.expect(log2_int(u32, 2) == 1);
try testing.expect(log2_int(u32, 3) == 1);
try testing.expect(log2_int(u32, 4) == 2);
try testing.expect(log2_int(u32, 5) == 2);
try testing.expect(log2_int(u32, 6) == 2);
try testing.expect(log2_int(u32, 7) == 2);
try testing.expect(log2_int(u32, 8) == 3);
try testing.expect(log2_int(u32, 9) == 3);
try testing.expect(log2_int(u32, 10) == 3);
}
std.math.log2_int_ceil
函数
返回整数值 x 以 2 为底的对数, 向上舍入到最近整数。
pub fn log2_int_ceil(comptime T: type, x: T) Log2IntCeil(T)
参数
T: type
x: T
用法示例
test log2_int_ceil {
try testing.expect(log2_int_ceil(u32, 1) == 0);
try testing.expect(log2_int_ceil(u32, 2) == 1);
try testing.expect(log2_int_ceil(u32, 3) == 2);
try testing.expect(log2_int_ceil(u32, 4) == 2);
try testing.expect(log2_int_ceil(u32, 5) == 3);
try testing.expect(log2_int_ceil(u32, 6) == 3);
try testing.expect(log2_int_ceil(u32, 7) == 3);
try testing.expect(log2_int_ceil(u32, 8) == 3);
try testing.expect(log2_int_ceil(u32, 9) == 4);
try testing.expect(log2_int_ceil(u32, 10) == 4);
}
std.math.log2e
常量
log2(e)
std.math.Log2Int
类型函数
返回可容纳 T 的位数减 1 的无符号整数类型。 适用于 T 的从 0 开始的位索引。
pub fn Log2Int(comptime T: type) type
参数
T: type
std.math.Log2IntCeil
类型函数
返回能够容纳 T 的位数的无符号整数类型。
pub fn Log2IntCeil(comptime T: type) type
参数
T: type
std.math.long_double
别名
std.math.lossyCast
函数
将值转换为另一类型。若该值超出新类型的范围, 或无法由新类型精确表示,则转换为 最接近的可表示值。
pub fn lossyCast(comptime T: type, value: anytype) T
参数
T: type
用法示例
test lossyCast {
try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));
try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));
try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));
try testing.expect(lossyCast(u32, @as(f32, @floatFromInt(maxInt(u32)))) == maxInt(u32));
try testing.expect(lossyCast(u32, nan(f32)) == 0);
}
std.math.maxInt
函数
返回整数类型 T 的最大值。
pub fn maxInt(comptime T: type) comptime_int
参数
T: type
用法示例
test maxInt {
try testing.expect(maxInt(u0) == 0);
try testing.expect(maxInt(u1) == 1);
try testing.expect(maxInt(u8) == 255);
try testing.expect(maxInt(u16) == 65535);
try testing.expect(maxInt(u32) == 4294967295);
try testing.expect(maxInt(u64) == 18446744073709551615);
try testing.expect(maxInt(u128) == 340282366920938463463374607431768211455);
try testing.expect(maxInt(i1) == 0);
try testing.expect(maxInt(i8) == 127);
try testing.expect(maxInt(i16) == 32767);
try testing.expect(maxInt(i32) == 2147483647);
try testing.expect(maxInt(i63) == 4611686018427387903);
try testing.expect(maxInt(i64) == 9223372036854775807);
try testing.expect(maxInt(i128) == 170141183460469231731687303715884105727);
}
std.math.mem
别名
别名目标 std.mem
std.math.Min
类型函数
给定两个类型,返回能容纳两者较小值完整 范围的最小类型。
pub fn Min(comptime A: type, comptime B: type) type
参数
A: type
B: type
std.math.minInt
函数
返回整数类型 T 的最小值。
pub fn minInt(comptime T: type) comptime_int
参数
T: type
用法示例
test minInt {
try testing.expect(minInt(u0) == 0);
try testing.expect(minInt(u1) == 0);
try testing.expect(minInt(u8) == 0);
try testing.expect(minInt(u16) == 0);
try testing.expect(minInt(u32) == 0);
try testing.expect(minInt(u63) == 0);
try testing.expect(minInt(u64) == 0);
try testing.expect(minInt(u128) == 0);
try testing.expect(minInt(i1) == -1);
try testing.expect(minInt(i8) == -128);
try testing.expect(minInt(i16) == -32768);
try testing.expect(minInt(i32) == -2147483648);
try testing.expect(minInt(i63) == -4611686018427387904);
try testing.expect(minInt(i64) == -9223372036854775808);
try testing.expect(minInt(i128) == -170141183460469231731687303715884105728);
}
std.math.mod
函数
返回分子对分母取模的结果;若分母为零或 负数则返回错误。分子为负时,返回值也 不会为负。
pub fn mod(comptime T: type, numerator: T, denominator: T) !T
参数
T: type
numerator: T
denominator: T
用法示例
test mod {
try testMod();
try comptime testMod();
}
std.math.modf
别名
别名目标 std.math.modf.modf
std.math.Modf
别名
别名目标 std.math.modf.Modf
std.math.mul
函数
返回 a 与 b 的乘积。溢出时返回错误。
pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T)
参数
T: type
a: T
b: T
std.math.mulWide
函数
计算 a 和 b 的乘积。返回类型足够宽,保证不会溢出。
pub fn mulWide(comptime T: type, a: T, b: T) @Int( @typeInfo(T).int.signedness, @typeInfo(T).int.bits * 2, )
参数
T: type
a: T
b: T
用法示例
test mulWide {
try testing.expect(mulWide(u8, 5, 5) == 25);
try testing.expect(mulWide(i8, 5, -5) == -25);
try testing.expect(mulWide(u8, 100, 100) == 10000);
}
std.math.nan
别名
别名目标 std.math.float.nan
std.math.negate
函数
pub fn negate(x: anytype) !@TypeOf(x)
std.math.negateCast
函数
返回整数参数的相反数。 结果为有符号整数。
pub fn negateCast(x: anytype) !@Int(.signed, @bitSizeOf(@TypeOf(x)))
用法示例
test negateCast {
try testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999);
try testing.expect(@TypeOf(negateCast(@as(u32, 999)) catch unreachable) == i32);
try testing.expect((negateCast(@as(u32, -minInt(i32))) catch unreachable) == minInt(i32));
try testing.expect(@TypeOf(negateCast(@as(u32, -minInt(i32))) catch unreachable) == i32);
try testing.expectError(error.Overflow, negateCast(@as(u32, maxInt(i32) + 10)));
}
std.math.nextAfter
别名
std.math.order
函数
给定两个数,返回它们彼此的大小关系。
pub fn order(a: anytype, b: anytype) Order
用法示例
test order {
try testing.expect(order(0, 0) == .eq);
try testing.expect(order(1, 0) == .gt);
try testing.expect(order(-1, 0) == .lt);
}
std.math.Order
容器
另见 CompareOperator。
字段
gt大于(>)
lt小于(<)
eq等于(==)
std.math.Order.compare
函数
pub fn compare(self: Order, op: CompareOperator) bool
参数
self: Order
op: CompareOperator
std.math.Order.differ
函数
pub fn differ(self: Order) ?Order
参数
self: Order
用法示例
test differ {
const neg: i32 = -1;
const zero: i32 = 0;
const pos: i32 = 1;
try testing.expect(order(zero, neg).differ() orelse
order(pos, zero) == .gt);
try testing.expect(order(zero, zero).differ() orelse
order(zero, zero) == .eq);
try testing.expect(order(pos, pos).differ() orelse
order(neg, zero) == .lt);
try testing.expect(order(zero, zero).differ() orelse
order(pos, neg).differ() orelse
order(neg, zero) == .gt);
try testing.expect(order(pos, pos).differ() orelse
order(pos, pos).differ() orelse
order(neg, neg) == .eq);
try testing.expect(order(zero, pos).differ() orelse
order(neg, pos).differ() orelse
order(pos, neg) == .lt);
}
std.math.Order.invert
函数
pub fn invert(self: Order) Order
参数
self: Order
用法示例
test invert {
try testing.expect(Order.invert(order(0, 0)) == .eq);
try testing.expect(Order.invert(order(1, 0)) == .lt);
try testing.expect(Order.invert(order(-1, 0)) == .gt);
}
std.math.phi
常量
黄金比例常量(Φ)= (1 + sqrt(5))/2
std.math.pi
常量
阿基米德常数(π)
std.math.pow
别名
别名目标 std.math.pow.pow
std.math.powi
别名
别名目标 std.math.powi.powi
std.math.rad_per_deg
常量
pi/180.0
std.math.radiansToDegrees
函数
将弧度转换为角度。T 必须是浮点数、编译时数值或浮点向量。
pub fn radiansToDegrees(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang)
用法示例
test radiansToDegrees {
const zero: f32 = 0;
const half_pi: f32 = pi / 2.0;
const neg_quart_pi: f32 = -pi / 4.0;
const one_pi: f32 = pi;
const two_pi: f32 = 2.0 * pi;
try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(zero), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(half_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(neg_quart_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 180), radiansToDegrees(one_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 360), radiansToDegrees(two_pi), 1e-6);
const result = radiansToDegrees(@Vector(4, f32){
half_pi,
neg_quart_pi,
one_pi,
two_pi,
});
try std.testing.expectApproxEqAbs(@as(f32, 90), result[0], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), result[1], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 180), result[2], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 360), result[3], 1e-6);
}
std.math.raiseDivByZero
函数
pub fn raiseDivByZero() void
std.math.raiseInexact
函数
pub fn raiseInexact() void
std.math.raiseInvalid
函数
pub fn raiseInvalid() void
std.math.raiseOverflow
函数
pub fn raiseOverflow() void
std.math.raiseUnderflow
函数
pub fn raiseUnderflow() void
std.math.rem
函数
返回 numerator 除以 denominator 的余数;若 denominator 为零或负数,则返回错误。负分子可能产生负结果。
pub fn rem(comptime T: type, numerator: T, denominator: T) !T
参数
T: type
numerator: T
denominator: T
用法示例
test rem {
try testRem();
try comptime testRem();
}
std.math.rotl
函数
循环左移。仅无符号值可进行循环移位。负移位量 会对位数取模后执行移位。
pub fn rotl(comptime T: type, x: T, r: anytype) T
参数
T: type
x: T
用法示例
test rotl {
try testing.expect(rotl(u0, 0b0, @as(usize, 3)) == 0b0);
try testing.expect(rotl(u5, 0b00001, @as(usize, 0)) == 0b00001);
try testing.expect(rotl(u6, 0b000001, @as(usize, 7)) == 0b000010);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
try testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000);
try testing.expect(rotl(u12, 0o7777, 1) == 0o7777);
try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(usize, 1))[0] == 1);
try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30);
try std.testing.expect(@reduce(.And, rotl(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) ==
@Vector(2, u0){ 0, 0 }));
}
std.math.rotr
函数
循环右移。仅无符号值可循环移位。 负移位值按位数取模后进行移位。
pub fn rotr(comptime T: type, x: T, r: anytype) T
参数
T: type
x: T
用法示例
test rotr {
try testing.expect(rotr(u0, 0b0, @as(usize, 3)) == 0b0);
try testing.expect(rotr(u5, 0b00001, @as(usize, 0)) == 0b00001);
try testing.expect(rotr(u6, 0b000001, @as(usize, 7)) == 0b100000);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 9)) == 0b10000000);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
try testing.expect(rotr(u8, 0b00000001, @as(isize, -1)) == 0b00000010);
try testing.expect(rotr(u12, 0o7777, 1) == 0o7777);
try testing.expect(rotr(@Vector(1, u32), .{1}, @as(usize, 1))[0] == @as(u32, 1) << 31);
try testing.expect(rotr(@Vector(1, u32), .{1}, @as(isize, -1))[0] == @as(u32, 1) << 1);
try std.testing.expect(@reduce(.And, rotr(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) ==
@Vector(2, u0){ 0, 0 }));
}
std.math.round
函数
将给定浮点数舍入到最近整数。 如果两个整数距离相同,则远离零舍入。 若可用,则使用专用硬件指令。 等同于调用内置函数 @round。
pub inline fn round(value: anytype) @TypeOf(value)
std.math.runTest
函数
fn runTest() !void
std.math.scalbn
别名
std.math.shl
函数
左移。溢出的位被截断。 移位量为负时执行右移。
pub fn shl(comptime T: type, a: T, shift_amt: anytype) T
参数
T: type
a: T
用法示例
test shl {
try testing.expect(shl(u8, 0b11111111, @as(usize, 3)) == 0b11111000);
try testing.expect(shl(u8, 0b11111111, @as(usize, 8)) == 0);
try testing.expect(shl(u8, 0b11111111, @as(usize, 9)) == 0);
try testing.expect(shl(u8, 0b11111111, @as(isize, -2)) == 0b00111111);
try testing.expect(shl(u8, 0b11111111, 3) == 0b11111000);
try testing.expect(shl(u8, 0b11111111, 8) == 0);
try testing.expect(shl(u8, 0b11111111, 9) == 0);
try testing.expect(shl(u8, 0b11111111, -2) == 0b00111111);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) << 1);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) >> 1);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0);
try testing.expect(shl(i8, -1, -100) == -1);
try testing.expect(shl(i8, -1, 100) == 0);
if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest;
try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ -1, 0 }));
try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ 0, 0 }));
}
std.math.shlExact
函数
将 a 左移 shift_amt 位。溢出时返回错误。shift_amt 为无符号数。
pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T
参数
std.math.shr
函数
右移。移出的位被截断。 负移位量表示左移。
pub fn shr(comptime T: type, a: T, shift_amt: anytype) T
参数
T: type
a: T
用法示例
test shr {
try testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111);
try testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0);
try testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0);
try testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100);
try testing.expect(shr(u8, 0b11111111, 3) == 0b00011111);
try testing.expect(shr(u8, 0b11111111, 8) == 0);
try testing.expect(shr(u8, 0b11111111, 9) == 0);
try testing.expect(shr(u8, 0b11111111, -2) == 0b11111100);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) >> 1);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) << 1);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0);
try testing.expect(shr(i8, -1, -100) == 0);
try testing.expect(shr(i8, -1, 100) == -1);
if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest;
try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ 0, 0 }));
try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ -1, 0 }));
}
std.math.sign
函数
返回 -1、0 或 1。 支持整数和浮点数类型,以及整数和浮点数向量。 无符号整数类型始终返回 0 或 1。 返回整数类型是足以容纳所有可能值的最小类型。 无分支。
pub inline fn sign(n: anytype) SignOf(@TypeOf(n))
用法示例
test sign {
try testSign();
try comptime testSign();
}
std.math.Sign
容器
字段
positive
negative
std.math.signbit
别名
std.math.signExtend
函数
通过复制最高有效位增大整数的位宽。 当按二进制补码整数解释时, 输入与输出具有相同的算术值。
pub fn signExtend(To: type, n: anytype) To
参数
To: type
用法示例
test signExtend {
const number: u8 = 0x86;
try testing.expectEqual(0xff86, signExtend(u16, number));
try testing.expectEqual(0, signExtend(u1, @as(u0, 0)));
try testing.expectEqual(0, signExtend(u16, @as(u0, 0)));
try testing.expectEqual(0x0000, signExtend(u16, @as(u1, 0b0)));
try testing.expectEqual(0xffff, signExtend(u16, @as(u1, 0b1)));
try testing.expectEqual(0b000, signExtend(u3, @as(u2, 0b00)));
try testing.expectEqual(0b001, signExtend(u3, @as(u2, 0b01)));
try testing.expectEqual(0b110, signExtend(u3, @as(u2, 0b10)));
try testing.expectEqual(0b111, signExtend(u3, @as(u2, 0b11)));
try testing.expectEqual(0b0000_0001, signExtend(u8, @as(u2, 0b01)));
try testing.expectEqual(0b1111_1110, signExtend(u8, @as(u2, 0b10)));
try testing.expectEqual(0x0039, signExtend(u16, @as(u8, 0x39)));
try testing.expectEqual(0xff93, signExtend(u16, @as(u8, 0x93)));
try testing.expectEqual(5, signExtend(i32, @as(i8, 5)));
try testing.expectEqual(-123, signExtend(i16, @as(i8, -123)));
}
std.math.SignOf
类型函数
fn SignOf(T: type) type
参数
T: type
std.math.sin
函数
浮点数的三角正弦函数。 若存在专用硬件指令,则使用该指令。 等价于调用内置函数 @sin。
pub inline fn sin(value: anytype) @TypeOf(value)
std.math.sinh
别名
别名目标 std.math.sinh.sinh
std.math.snan
别名
别名目标 std.math.float.snan
std.math.sqrt
别名
别名目标 std.math.sqrt.sqrt
std.math.sqrt1_2
常量
1/sqrt(2)
std.math.sqrt2
常量
sqrt(2)
std.math.std
别名
别名目标 std
std.math.sub
函数
返回 a - b,溢出时返回错误。
pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T)
参数
T: type
a: T
b: T
std.math.tan
函数
计算浮点数的正切三角函数。 若可用,则使用专用硬件指令。 等同于调用内置函数 @tan。
pub inline fn tan(value: anytype) @TypeOf(value)
std.math.tanh
别名
别名目标 std.math.tanh.tanh
std.math.tau
常量
圆周常数(τ)
std.math.testCeilPowerOfTwo
函数
fn testCeilPowerOfTwo() !void
std.math.testCeilPowerOfTwoPromote
函数
fn testCeilPowerOfTwoPromote() !void
std.math.testDivCeil
函数
fn testDivCeil() !void
std.math.testDivExact
函数
fn testDivExact() !void
std.math.testDivFloor
函数
fn testDivFloor() !void
std.math.testDivTrunc
函数
fn testDivTrunc() !void
std.math.testFloorPowerOfTwo
函数
fn testFloorPowerOfTwo() !void
std.math.testing
别名
别名目标 std.testing
std.math.testMod
函数
fn testMod() !void
std.math.testOverflow
函数
fn testOverflow() !void
std.math.testRem
函数
fn testRem() !void
std.math.testSign
函数
fn testSign() !void
std.math.trunc
函数
将给定浮点数向零舍入为整数。 若可用,则使用专门的硬件指令。 与调用内置函数 @trunc 相同。
pub inline fn trunc(value: anytype) @TypeOf(value)
std.math.two_sqrtpi
常量
2/sqrt(π)
std.math.wrap
函数
奇对称锯齿函数
|
/ | / /
/ |/ /
--/----/----/--
/ /| /
/ / | /
|
将 x 限制在半开区间 [-r, r) 内。
pub fn wrap(x: anytype, r: anytype) @TypeOf(x)
用法示例
test wrap {
if (builtin.os.tag == .windows and builtin.cpu.arch == .x86 and builtin.abi == .msvc) {
// https://codeberg.org/ziglang/zig/issues/35520
return error.SkipZigTest;
}
// 位于范围内
try testing.expect(wrap(@as(i32, -75), @as(i32, 180)) == -75);
try testing.expect(wrap(@as(i32, -75), @as(i32, -180)) == -75);
// 下方
try testing.expect(wrap(@as(i32, -225), @as(i32, 180)) == 135);
try testing.expect(wrap(@as(i32, -225), @as(i32, -180)) == 135);
// 上方
try testing.expect(wrap(@as(i32, 361), @as(i32, 180)) == 1);
try testing.expect(wrap(@as(i32, 361), @as(i32, -180)) == 1);
// 一个周期、右极限、正 r
try testing.expect(wrap(@as(i32, 180), @as(i32, 180)) == -180);
// 一个周期,左侧极限,正 r
try testing.expect(wrap(@as(i32, -180), @as(i32, 180)) == -180);
// 一个周期,右极限,r 为负
try testing.expect(wrap(@as(i32, 180), @as(i32, -180)) == 180);
// 一个周期、左极限、负 r
try testing.expect(wrap(@as(i32, -180), @as(i32, -180)) == 180);
// 两个周期,右极限,r 为正
try testing.expect(wrap(@as(i32, 540), @as(i32, 180)) == -180);
// 两个周期,左侧极限,正 r
try testing.expect(wrap(@as(i32, -540), @as(i32, 180)) == -180);
// 两个周期,右侧极限,负 r
try testing.expect(wrap(@as(i32, 540), @as(i32, -180)) == 180);
// 两个周期、左极限、负 r
try testing.expect(wrap(@as(i32, -540), @as(i32, -180)) == 180);
// 浮点数
try testing.expect(wrap(@as(f32, 1.125), @as(f32, 1.0)) == -0.875);
try testing.expect(wrap(@as(f32, -127.5), @as(f32, 180)) == -127.5);
// 编译期与非编译期内容混合
var i: i32 = 1;
_ = &i;
try testing.expect(wrap(i, 10) == 1);
const limit: i32 = 180;
// 位于范围内
try testing.expect(wrap(@as(i32, -75), limit) == -75);
// 下方
try testing.expect(wrap(@as(i32, -225), limit) == 135);
// 上方
try testing.expect(wrap(@as(i32, 361), limit) == 1);
}
源码
std/math.zig
const builtin = @import("builtin");
const std = @import("std.zig");
const float = @import("math/float.zig");
const assert = std.debug.assert;
const mem = std.mem;
const testing = std.testing;
const Alignment = std.mem.Alignment;
/// 欧拉数(e)
pub const e = 2.71828182845904523536028747135266249775724709369995;
/// 阿基米德常数(π)
pub const pi = 3.14159265358979323846264338327950288419716939937510;
/// 黄金比例常量(Φ)= (1 + sqrt(5))/2
pub const phi = 1.6180339887498948482045868343656381177203091798057628621;
/// 圆周常数(τ)
pub const tau = 2 * pi;
/// log2(e)
pub const log2e = 1.442695040888963407359924681001892137;
/// log10(e)
pub const log10e = 0.434294481903251827651128918916605082;
/// ln(2)
pub const ln2 = 0.693147180559945309417232121458176568;
/// ln(10)
pub const ln10 = 2.302585092994045684017991454684364208;
/// 2/sqrt(π)
pub const two_sqrtpi = 1.128379167095512573896158903121545172;
/// sqrt(2)
pub const sqrt2 = 1.414213562373095048801688724209698079;
/// 1/sqrt(2)
pub const sqrt1_2 = 0.707106781186547524400844362104849039;
/// pi/180.0
pub const rad_per_deg = 0.0174532925199432957692369076848861271344287188854172545609719144;
/// 180.0/pi
pub const deg_per_rad = 57.295779513082320876798154814105170332405472466564321549160243861;
pub const Sign = enum(u1) { positive, negative };
pub const FloatRepr = float.FloatRepr;
pub const floatExponentBits = float.floatExponentBits;
pub const floatMantissaBits = float.floatMantissaBits;
pub const floatFractionalBits = float.floatFractionalBits;
pub const floatExponentMin = float.floatExponentMin;
pub const floatExponentMax = float.floatExponentMax;
pub const floatTrueMin = float.floatTrueMin;
pub const floatMin = float.floatMin;
pub const floatMax = float.floatMax;
pub const floatEps = float.floatEps;
pub const floatEpsAt = float.floatEpsAt;
pub const inf = float.inf;
pub const long_double = float.long_double;
pub const nan = float.nan;
pub const snan = float.snan;
/// 近似比较两个浮点值 `x` 和 `y`。
/// 如果二者的绝对差小于或等于
/// 指定容差,则返回 true。
///
/// `tolerance` 参数是判断两个数是否足够
/// 接近时使用的绝对容差;较好的取值为
/// `floatEps(T)` 的一个较小倍数。
///
/// 注意,建议使用此函数比较零附近的
/// 较小数;其他情况下建议使用 `approxEqRel`。
///
/// NaN 值绝不会被视为与任何值相等。
pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {
comptime assert(@typeInfo(T) == .float or @typeInfo(T) == .comptime_float);
assert(tolerance >= 0);
// 相等值的快速路径(也包含有符号零和无穷大)。
if (x == y)
return true;
if (isNan(x) or isNan(y))
return false;
return @abs(x - y) <= tolerance;
}
/// 对两个浮点值 `x` 和 `y` 进行近似比较。
/// 若它们的绝对差小于或等于
/// `max(|x|, |y|) * tolerance`,则返回 true,其中 `tolerance` 是
/// 大于零的正数。
///
/// `tolerance` 参数是判断两个数是否足够接近时使用的
/// 相对容差;此参数通常可取
/// `sqrt(floatEps(T))`,意为至少一半数位相同时,
/// 便将两个数视为相等。
///
/// 注意:比较接近零的小数值时,此函数
/// 不会给出有意义的结果,应改用 `approxEqAbs`。
///
/// NaN 与任何值都不被视为相等。
pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool {
comptime assert(@typeInfo(T) == .float or @typeInfo(T) == .comptime_float);
assert(tolerance > 0);
// 相等值的快速路径(也包含有符号零和无穷大)。
if (x == y)
return true;
if (isNan(x) or isNan(y))
return false;
return @abs(x - y) <= @max(@abs(x), @abs(y)) * tolerance;
}
test approxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value));
try testing.expect(!approxEqAbs(T, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, 1.0 + 1 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2));
try testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2));
}
comptime {
// `comptime_float` 保证具有其他最大浮点类型,即 f128 的
// 精度和运算,但它没有
// 定义明确的布局,因此不能像上方测试那样,依靠 `@bitCast`
// 构造最小的 epsilon 值。同样,
// 也无法表示最大/最小值、`NaN` 或 `Inf`。
const eps_value = 1e-4;
try testing.expect(approxEqAbs(comptime_float, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 0.0, -0.0, eps_value));
try testing.expect(!approxEqAbs(comptime_float, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 1.0 + 1 * eps_value, 1.0, eps_value));
}
}
test approxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const sqrt_eps_value = comptime sqrt(eps_value);
const nan_value = comptime nan(T);
const inf_value = comptime inf(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value));
try testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value));
}
comptime {
// `comptime_float` 保证具有其他最大浮点类型,即 f128 的
// 精度和运算,但它没有
// 定义明确的布局,因此不能像上方测试那样,依靠 `@bitCast`
// 构造最小的 epsilon 值。同样,
// 也无法表示最大/最小值、`NaN` 或 `Inf`。
const eps_value = 1e-4;
const sqrt_eps_value = sqrt(eps_value);
try testing.expect(approxEqRel(comptime_float, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(comptime_float, 1.0, 0.0, sqrt_eps_value));
}
}
pub fn raiseInvalid() void {
// 引发 INVALID 浮点单元异常
}
pub fn raiseUnderflow() void {
// 引发 UNDERFLOW 浮点单元异常
}
pub fn raiseOverflow() void {
// 触发浮点单元 OVERFLOW 异常
}
pub fn raiseInexact() void {
// 触发 INEXACT 浮点异常
}
pub fn raiseDivByZero() void {
// 触发 INEXACT 浮点异常
}
pub const isNan = @import("math/isnan.zig").isNan;
pub const isSignalNan = @import("math/isnan.zig").isSignalNan;
pub const frexp = @import("math/frexp.zig").frexp;
pub const Frexp = @import("math/frexp.zig").Frexp;
pub const modf = @import("math/modf.zig").modf;
pub const Modf = @import("math/modf.zig").Modf;
pub const copysign = @import("math/copysign.zig").copysign;
pub const isFinite = @import("math/isfinite.zig").isFinite;
pub const isInf = @import("math/isinf.zig").isInf;
pub const isPositiveInf = @import("math/isinf.zig").isPositiveInf;
pub const isNegativeInf = @import("math/isinf.zig").isNegativeInf;
pub const isPositiveZero = @import("math/iszero.zig").isPositiveZero;
pub const isNegativeZero = @import("math/iszero.zig").isNegativeZero;
pub const isNormal = @import("math/isnormal.zig").isNormal;
pub const nextAfter = @import("math/nextafter.zig").nextAfter;
pub const signbit = @import("math/signbit.zig").signbit;
pub const scalbn = @import("math/scalbn.zig").scalbn;
pub const ldexp = @import("math/ldexp.zig").ldexp;
pub const pow = @import("math/pow.zig").pow;
pub const powi = @import("math/powi.zig").powi;
pub const sqrt = @import("math/sqrt.zig").sqrt;
pub const cbrt = @import("math/cbrt.zig").cbrt;
pub const acos = @import("math/acos.zig").acos;
pub const asin = @import("math/asin.zig").asin;
pub const atan = @import("math/atan.zig").atan;
pub const atan2 = @import("math/atan2.zig").atan2;
pub const hypot = @import("math/hypot.zig").hypot;
pub const expm1 = @import("math/expm1.zig").expm1;
pub const ilogb = @import("math/ilogb.zig").ilogb;
pub const log = @import("math/log.zig").log;
pub const log2 = @import("math/log2.zig").log2;
pub const log10 = @import("math/log10.zig").log10;
pub const log10_int = @import("math/log10.zig").log10_int;
pub const log_int = @import("math/log_int.zig").log_int;
pub const log1p = @import("math/log1p.zig").log1p;
pub const asinh = @import("math/asinh.zig").asinh;
pub const acosh = @import("math/acosh.zig").acosh;
pub const atanh = @import("math/atanh.zig").atanh;
pub const sinh = @import("math/sinh.zig").sinh;
pub const cosh = @import("math/cosh.zig").cosh;
pub const tanh = @import("math/tanh.zig").tanh;
pub const gcd = @import("math/gcd.zig").gcd;
pub const lcm = @import("math/lcm.zig").lcm;
pub const gamma = @import("math/gamma.zig").gamma;
pub const lgamma = @import("math/gamma.zig").lgamma;
/// 浮点数的三角正弦函数。
/// 若存在专用硬件指令,则使用该指令。
/// 等价于调用内置函数 @sin。
pub inline fn sin(value: anytype) @TypeOf(value) {
return @sin(value);
}
/// 浮点数的三角余弦函数。
/// 若可用,则使用专用硬件指令。
/// 等同于调用内置函数 @cos
pub inline fn cos(value: anytype) @TypeOf(value) {
return @cos(value);
}
/// 计算浮点数的正切三角函数。
/// 若可用,则使用专用硬件指令。
/// 等同于调用内置函数 @tan。
pub inline fn tan(value: anytype) @TypeOf(value) {
return @tan(value);
}
/// 将弧度转换为角度。T 必须是浮点数、编译时数值或浮点向量。
pub fn radiansToDegrees(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang) {
const T = @TypeOf(ang);
switch (@typeInfo(T)) {
.float, .comptime_float, .comptime_int => return ang * deg_per_rad,
.vector => |V| if (@typeInfo(V.child) == .float) return ang * @as(T, @splat(deg_per_rad)),
else => {},
}
@compileError("Input must be float or a comptime number, or a vector of floats.");
}
test radiansToDegrees {
const zero: f32 = 0;
const half_pi: f32 = pi / 2.0;
const neg_quart_pi: f32 = -pi / 4.0;
const one_pi: f32 = pi;
const two_pi: f32 = 2.0 * pi;
try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(zero), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(half_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(neg_quart_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 180), radiansToDegrees(one_pi), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 360), radiansToDegrees(two_pi), 1e-6);
const result = radiansToDegrees(@Vector(4, f32){
half_pi,
neg_quart_pi,
one_pi,
two_pi,
});
try std.testing.expectApproxEqAbs(@as(f32, 90), result[0], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), result[1], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 180), result[2], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 360), result[3], 1e-6);
}
/// 将角度从度转换为弧度。T 必须为浮点数、编译期数值或浮点向量。
pub fn degreesToRadians(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang) {
const T = @TypeOf(ang);
switch (@typeInfo(T)) {
.float, .comptime_float, .comptime_int => return ang * rad_per_deg,
.vector => |V| if (@typeInfo(V.child) == .float) return ang * @as(T, @splat(rad_per_deg)),
else => {},
}
@compileError("Input must be float or a comptime number, or a vector of floats.");
}
test degreesToRadians {
const ninety: f32 = 90;
const neg_two_seventy: f32 = -270;
const three_sixty: f32 = 360;
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(ninety), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(neg_two_seventy), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(three_sixty), 1e-6);
const result = degreesToRadians(@Vector(3, f32){
ninety,
neg_two_seventy,
three_sixty,
});
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), result[0], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), result[1], 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), result[2], 1e-6);
}
/// 计算浮点数的以 e 为底的指数函数。
/// 若可用,则使用专用硬件指令。
/// 等同于调用内置函数 @exp。
pub inline fn exp(value: anytype) @TypeOf(value) {
return @exp(value);
}
/// 计算浮点数的以 2 为底的指数函数。
/// 若可用,则使用专用硬件指令。
/// 等同于调用内置函数 @exp2。
pub inline fn exp2(value: anytype) @TypeOf(value) {
return @exp2(value);
}
pub const complex = @import("math/complex.zig");
pub const Complex = complex.Complex;
pub const big = @import("math/big.zig");
test {
_ = floatExponentBits;
_ = floatMantissaBits;
_ = floatFractionalBits;
_ = floatExponentMin;
_ = floatExponentMax;
_ = floatTrueMin;
_ = floatMin;
_ = floatMax;
_ = floatEps;
_ = inf;
_ = nan;
_ = snan;
_ = isNan;
_ = isSignalNan;
_ = frexp;
_ = Frexp;
_ = modf;
_ = Modf;
_ = copysign;
_ = isFinite;
_ = isInf;
_ = isPositiveInf;
_ = isNegativeInf;
_ = isNormal;
_ = nextAfter;
_ = signbit;
_ = scalbn;
_ = ldexp;
_ = pow;
_ = powi;
_ = sqrt;
_ = cbrt;
_ = acos;
_ = asin;
_ = atan;
_ = atan2;
_ = hypot;
_ = expm1;
_ = ilogb;
_ = log;
_ = log2;
_ = log10;
_ = log10_int;
_ = log_int;
_ = log1p;
_ = asinh;
_ = acosh;
_ = atanh;
_ = sinh;
_ = cosh;
_ = tanh;
_ = gcd;
_ = lcm;
_ = gamma;
_ = lgamma;
_ = complex;
_ = Complex;
_ = big;
}
/// 给定两个类型,返回能容纳两者较小值完整
/// 范围的最小类型。
pub fn Min(comptime A: type, comptime B: type) type {
switch (@typeInfo(A)) {
.int => |a_info| switch (@typeInfo(B)) {
.int => |b_info| if (a_info.signedness == .unsigned and b_info.signedness == .unsigned) {
if (a_info.bits < b_info.bits) {
return A;
} else {
return B;
}
},
else => {},
},
else => {},
}
return @TypeOf(@as(A, 0) + @as(B, 0));
}
/// 奇对称锯齿函数
/// ```
/// |
/// / | / /
/// / |/ /
/// --/----/----/--
/// / /| /
/// / / | /
/// |
/// ```
/// 将 x 限制在半开区间 [-r, r) 内。
pub fn wrap(x: anytype, r: anytype) @TypeOf(x) {
const info_x = @typeInfo(@TypeOf(x));
const info_r = @typeInfo(@TypeOf(r));
if (info_x == .int and info_x.int.signedness != .signed) {
@compileError("x must be floating point, comptime integer, or signed integer.");
}
switch (info_r) {
.int => {
// 在 r 既不是 comptime_int 也不是浮点类型的少见情况下,
// 接受中间类型转换的开销;
// 另一种办法则是迭代展开,以避免溢出。
const R = @Int(.signed, info_r.int.bits + 1);
const radius: if (info_r.int.signedness == .signed) @TypeOf(r) else R = r;
return @intCast(@mod(x - radius, 2 * @as(R, r)) - r); // 可证明不可能溢出
},
else => {
return @mod(x - r, 2 * r) - r;
},
}
}
test wrap {
if (builtin.os.tag == .windows and builtin.cpu.arch == .x86 and builtin.abi == .msvc) {
// https://codeberg.org/ziglang/zig/issues/35520
return error.SkipZigTest;
}
// 位于范围内
try testing.expect(wrap(@as(i32, -75), @as(i32, 180)) == -75);
try testing.expect(wrap(@as(i32, -75), @as(i32, -180)) == -75);
// 下方
try testing.expect(wrap(@as(i32, -225), @as(i32, 180)) == 135);
try testing.expect(wrap(@as(i32, -225), @as(i32, -180)) == 135);
// 上方
try testing.expect(wrap(@as(i32, 361), @as(i32, 180)) == 1);
try testing.expect(wrap(@as(i32, 361), @as(i32, -180)) == 1);
// 一个周期、右极限、正 r
try testing.expect(wrap(@as(i32, 180), @as(i32, 180)) == -180);
// 一个周期,左侧极限,正 r
try testing.expect(wrap(@as(i32, -180), @as(i32, 180)) == -180);
// 一个周期,右极限,r 为负
try testing.expect(wrap(@as(i32, 180), @as(i32, -180)) == 180);
// 一个周期、左极限、负 r
try testing.expect(wrap(@as(i32, -180), @as(i32, -180)) == 180);
// 两个周期,右极限,r 为正
try testing.expect(wrap(@as(i32, 540), @as(i32, 180)) == -180);
// 两个周期,左侧极限,正 r
try testing.expect(wrap(@as(i32, -540), @as(i32, 180)) == -180);
// 两个周期,右侧极限,负 r
try testing.expect(wrap(@as(i32, 540), @as(i32, -180)) == 180);
// 两个周期、左极限、负 r
try testing.expect(wrap(@as(i32, -540), @as(i32, -180)) == 180);
// 浮点数
try testing.expect(wrap(@as(f32, 1.125), @as(f32, 1.0)) == -0.875);
try testing.expect(wrap(@as(f32, -127.5), @as(f32, 180)) == -127.5);
// 编译期与非编译期内容混合
var i: i32 = 1;
_ = &i;
try testing.expect(wrap(i, 10) == 1);
const limit: i32 = 180;
// 位于范围内
try testing.expect(wrap(@as(i32, -75), limit) == -75);
// 下方
try testing.expect(wrap(@as(i32, -225), limit) == 135);
// 上方
try testing.expect(wrap(@as(i32, 361), limit) == 1);
}
/// 奇对称斜坡函数。
/// ```
/// | _____
/// | /
/// |/
/// -------/-------
/// /|
/// _____/ |
/// |
/// ```
/// 将 val 限制在闭区间 [lower, upper] 内。
pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
const T = @TypeOf(val, lower, upper);
switch (@typeInfo(T)) {
.int, .float, .comptime_int, .comptime_float => assert(lower <= upper),
.vector => |vinfo| switch (@typeInfo(vinfo.child)) {
.int, .float => assert(@reduce(.And, lower <= upper)),
else => @compileError("Expected vector of ints or floats, found " ++ @typeName(T)),
},
else => @compileError("Expected an int, float or vector of one, found " ++ @typeName(T)),
}
return @max(lower, @min(val, upper));
}
test clamp {
// 位于范围内
try testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1);
// 下方
try testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4);
// 上方
try testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
// 浮点数
try testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
try testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
// 向量
try testing.expect(@reduce(.And, std.math.clamp(@as(@Vector(3, f32), .{ 1.4, 15.23, 28.3 }), @as(@Vector(3, f32), .{ 9.8, 13.2, 15.6 }), @as(@Vector(3, f32), .{ 15.2, 22.8, 26.3 })) == @as(@Vector(3, f32), .{ 9.8, 15.23, 26.3 })));
// 编译期与非编译期内容混合
var i: i32 = 1;
_ = &i;
try testing.expect(std.math.clamp(i, 0, 1) == 1);
}
/// 返回 a 与 b 的乘积。溢出时返回错误。
pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {
if (T == comptime_int) return a * b;
const ov = @mulWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
/// 返回 a 与 b 的和。溢出时返回错误。
pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) {
if (T == comptime_int) return a + b;
const ov = @addWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
/// 返回 a - b,溢出时返回错误。
pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) {
if (T == comptime_int) return a - b;
const ov = @subWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
pub fn negate(x: anytype) !@TypeOf(x) {
return sub(@TypeOf(x), 0, x);
}
/// 将 a 左移 shift_amt 位。溢出时返回错误。shift_amt 为无符号数。
///
pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T {
if (T == comptime_int) return a << shift_amt;
const ov = @shlWithOverflow(a, shift_amt);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
/// 左移。溢出的位被截断。
/// 移位量为负时执行右移。
pub fn shl(comptime T: type, a: T, shift_amt: anytype) T {
const is_shl = shift_amt >= 0;
const abs_shift_amt = @abs(shift_amt);
const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) {
.int => |info| {
if (abs_shift_amt < info.bits) break :casted_shift_amt @as(
Log2Int(T),
@intCast(abs_shift_amt),
);
if (info.signedness == .unsigned or is_shl) return 0;
return a >> (info.bits - 1);
},
.vector => |info| {
const Child = info.child;
const child_info = @typeInfo(Child).int;
if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as(
@Vector(info.len, Log2Int(Child)),
@splat(@as(Log2Int(Child), @intCast(abs_shift_amt))),
);
if (child_info.signedness == .unsigned or is_shl) return @splat(0);
return a >> @splat(child_info.bits - 1);
},
else => comptime unreachable,
};
return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt;
}
test shl {
try testing.expect(shl(u8, 0b11111111, @as(usize, 3)) == 0b11111000);
try testing.expect(shl(u8, 0b11111111, @as(usize, 8)) == 0);
try testing.expect(shl(u8, 0b11111111, @as(usize, 9)) == 0);
try testing.expect(shl(u8, 0b11111111, @as(isize, -2)) == 0b00111111);
try testing.expect(shl(u8, 0b11111111, 3) == 0b11111000);
try testing.expect(shl(u8, 0b11111111, 8) == 0);
try testing.expect(shl(u8, 0b11111111, 9) == 0);
try testing.expect(shl(u8, 0b11111111, -2) == 0b00111111);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) << 1);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) >> 1);
try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0);
try testing.expect(shl(i8, -1, -100) == -1);
try testing.expect(shl(i8, -1, 100) == 0);
if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest;
try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ -1, 0 }));
try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ 0, 0 }));
}
/// 右移。移出的位被截断。
/// 负移位量表示左移。
pub fn shr(comptime T: type, a: T, shift_amt: anytype) T {
const is_shl = shift_amt < 0;
const abs_shift_amt = @abs(shift_amt);
const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) {
.int => |info| {
if (abs_shift_amt < info.bits) break :casted_shift_amt @as(
Log2Int(T),
@intCast(abs_shift_amt),
);
if (info.signedness == .unsigned or is_shl) return 0;
return a >> (info.bits - 1);
},
.vector => |info| {
const Child = info.child;
const child_info = @typeInfo(Child).int;
if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as(
@Vector(info.len, Log2Int(Child)),
@splat(@as(Log2Int(Child), @intCast(abs_shift_amt))),
);
if (child_info.signedness == .unsigned or is_shl) return @splat(0);
return a >> @splat(child_info.bits - 1);
},
else => comptime unreachable,
};
return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt;
}
test shr {
try testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111);
try testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0);
try testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0);
try testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100);
try testing.expect(shr(u8, 0b11111111, 3) == 0b00011111);
try testing.expect(shr(u8, 0b11111111, 8) == 0);
try testing.expect(shr(u8, 0b11111111, 9) == 0);
try testing.expect(shr(u8, 0b11111111, -2) == 0b11111100);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) >> 1);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) << 1);
try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0);
try testing.expect(shr(i8, -1, -100) == 0);
try testing.expect(shr(i8, -1, 100) == -1);
if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest;
try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ 0, 0 }));
try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ -1, 0 }));
}
/// 循环右移。仅无符号值可循环移位。
/// 负移位值按位数取模后进行移位。
pub fn rotr(comptime T: type, x: T, r: anytype) T {
if (@typeInfo(T) == .vector) {
const C = @typeInfo(T).vector.child;
if (C == u0) return @splat(0);
if (@typeInfo(C).int.signedness == .signed) {
@compileError("cannot rotate signed integers");
}
const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits));
return (x >> @splat(ar)) | (x << @splat(1 + ~ar));
} else if (@typeInfo(T).int.signedness == .signed) {
@compileError("cannot rotate signed integer");
} else {
if (T == u0) return 0;
if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) {
const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits));
return x >> ar | x << (1 +% ~ar);
} else {
const ar = @mod(r, @typeInfo(T).int.bits);
return shr(T, x, ar) | shl(T, x, @typeInfo(T).int.bits - ar);
}
}
}
test rotr {
try testing.expect(rotr(u0, 0b0, @as(usize, 3)) == 0b0);
try testing.expect(rotr(u5, 0b00001, @as(usize, 0)) == 0b00001);
try testing.expect(rotr(u6, 0b000001, @as(usize, 7)) == 0b100000);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 9)) == 0b10000000);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
try testing.expect(rotr(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
try testing.expect(rotr(u8, 0b00000001, @as(isize, -1)) == 0b00000010);
try testing.expect(rotr(u12, 0o7777, 1) == 0o7777);
try testing.expect(rotr(@Vector(1, u32), .{1}, @as(usize, 1))[0] == @as(u32, 1) << 31);
try testing.expect(rotr(@Vector(1, u32), .{1}, @as(isize, -1))[0] == @as(u32, 1) << 1);
try std.testing.expect(@reduce(.And, rotr(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) ==
@Vector(2, u0){ 0, 0 }));
}
/// 循环左移。仅无符号值可进行循环移位。负移位量
/// 会对位数取模后执行移位。
pub fn rotl(comptime T: type, x: T, r: anytype) T {
if (@typeInfo(T) == .vector) {
const C = @typeInfo(T).vector.child;
if (C == u0) return @splat(0);
if (@typeInfo(C).int.signedness == .signed) {
@compileError("cannot rotate signed integers");
}
const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits));
return (x << @splat(ar)) | (x >> @splat(1 +% ~ar));
} else if (@typeInfo(T).int.signedness == .signed) {
@compileError("cannot rotate signed integer");
} else {
if (T == u0) return 0;
if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) {
const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits));
return x << ar | x >> 1 +% ~ar;
} else {
const ar = @mod(r, @typeInfo(T).int.bits);
return shl(T, x, ar) | shr(T, x, @typeInfo(T).int.bits - ar);
}
}
}
test rotl {
try testing.expect(rotl(u0, 0b0, @as(usize, 3)) == 0b0);
try testing.expect(rotl(u5, 0b00001, @as(usize, 0)) == 0b00001);
try testing.expect(rotl(u6, 0b000001, @as(usize, 7)) == 0b000010);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
try testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
try testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000);
try testing.expect(rotl(u12, 0o7777, 1) == 0o7777);
try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(usize, 1))[0] == 1);
try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30);
try std.testing.expect(@reduce(.And, rotl(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) ==
@Vector(2, u0){ 0, 0 }));
}
/// 返回可容纳 T 的位数减 1 的无符号整数类型。
/// 适用于 T 的从 0 开始的位索引。
pub fn Log2Int(comptime T: type) type {
// 编译时向上取整 log2
if (T == comptime_int) return comptime_int;
const bits: u16 = @typeInfo(T).int.bits;
const log2_bits = 16 - @clz(bits - 1);
return @Int(.unsigned, log2_bits);
}
/// 返回能够容纳 T 的位数的无符号整数类型。
pub fn Log2IntCeil(comptime T: type) type {
// 编译时向上取整 log2
if (T == comptime_int) return comptime_int;
const bits: u16 = @typeInfo(T).int.bits;
const log2_bits = 16 - @clz(bits);
return @Int(.unsigned, log2_bits);
}
/// 返回能同时容纳 from 和 to 的最小整数类型。
pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type {
assert(from <= to);
const signedness: std.builtin.Signedness = if (from < 0) .signed else .unsigned;
return @Int(
signedness,
@as(u16, @intFromBool(signedness == .signed)) +
switch (if (from < 0) @max(@abs(from) - 1, to) else to) {
0 => 0,
else => |pos_max| 1 + log2(pos_max),
},
);
}
test IntFittingRange {
try testing.expect(IntFittingRange(0, 0) == u0);
try testing.expect(IntFittingRange(0, 1) == u1);
try testing.expect(IntFittingRange(0, 2) == u2);
try testing.expect(IntFittingRange(0, 3) == u2);
try testing.expect(IntFittingRange(0, 4) == u3);
try testing.expect(IntFittingRange(0, 7) == u3);
try testing.expect(IntFittingRange(0, 8) == u4);
try testing.expect(IntFittingRange(0, 9) == u4);
try testing.expect(IntFittingRange(0, 15) == u4);
try testing.expect(IntFittingRange(0, 16) == u5);
try testing.expect(IntFittingRange(0, 17) == u5);
try testing.expect(IntFittingRange(0, 4095) == u12);
try testing.expect(IntFittingRange(2000, 4095) == u12);
try testing.expect(IntFittingRange(0, 4096) == u13);
try testing.expect(IntFittingRange(2000, 4096) == u13);
try testing.expect(IntFittingRange(0, 4097) == u13);
try testing.expect(IntFittingRange(2000, 4097) == u13);
try testing.expect(IntFittingRange(0, 123456789123456798123456789) == u87);
try testing.expect(IntFittingRange(0, 123456789123456798123456789123456789123456798123456789) == u177);
try testing.expect(IntFittingRange(-1, -1) == i1);
try testing.expect(IntFittingRange(-1, 0) == i1);
try testing.expect(IntFittingRange(-1, 1) == i2);
try testing.expect(IntFittingRange(-2, -2) == i2);
try testing.expect(IntFittingRange(-2, -1) == i2);
try testing.expect(IntFittingRange(-2, 0) == i2);
try testing.expect(IntFittingRange(-2, 1) == i2);
try testing.expect(IntFittingRange(-2, 2) == i3);
try testing.expect(IntFittingRange(-1, 2) == i3);
try testing.expect(IntFittingRange(-1, 3) == i3);
try testing.expect(IntFittingRange(-1, 4) == i4);
try testing.expect(IntFittingRange(-1, 7) == i4);
try testing.expect(IntFittingRange(-1, 8) == i5);
try testing.expect(IntFittingRange(-1, 9) == i5);
try testing.expect(IntFittingRange(-1, 15) == i5);
try testing.expect(IntFittingRange(-1, 16) == i6);
try testing.expect(IntFittingRange(-1, 17) == i6);
try testing.expect(IntFittingRange(-1, 4095) == i13);
try testing.expect(IntFittingRange(-4096, 4095) == i13);
try testing.expect(IntFittingRange(-1, 4096) == i14);
try testing.expect(IntFittingRange(-4097, 4095) == i14);
try testing.expect(IntFittingRange(-1, 4097) == i14);
try testing.expect(IntFittingRange(-1, 123456789123456798123456789) == i88);
try testing.expect(IntFittingRange(-1, 123456789123456798123456789123456789123456798123456789) == i178);
}
test "overflow functions" {
try testOverflow();
try comptime testOverflow();
}
fn testOverflow() !void {
try testing.expect((mul(i32, 3, 4) catch unreachable) == 12);
try testing.expect((add(i32, 3, 4) catch unreachable) == 7);
try testing.expect((sub(i32, 3, 4) catch unreachable) == -1);
try testing.expect((shlExact(i32, 0b11, 4) catch unreachable) == 0b110000);
}
/// 计算分子除以分母的商,向零取整。溢出或
/// 分母为零时返回错误。
pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
return @divTrunc(numerator, denominator);
}
test divTrunc {
try testDivTrunc();
try comptime testDivTrunc();
}
fn testDivTrunc() !void {
try testing.expect((divTrunc(i32, 5, 3) catch unreachable) == 1);
try testing.expect((divTrunc(i32, -5, 3) catch unreachable) == -1);
try testing.expectError(error.DivisionByZero, divTrunc(i8, -5, 0));
try testing.expectError(error.Overflow, divTrunc(i8, -128, -1));
try testing.expect((divTrunc(f32, 5.0, 3.0) catch unreachable) == 1.0);
try testing.expect((divTrunc(f32, -5.0, 3.0) catch unreachable) == -1.0);
}
/// 计算分子除以分母的商,向负
/// 无穷取整。溢出或分母为
/// 零时返回错误。
pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
return @divFloor(numerator, denominator);
}
test divFloor {
try testDivFloor();
try comptime testDivFloor();
}
fn testDivFloor() !void {
try testing.expect((divFloor(i32, 5, 3) catch unreachable) == 1);
try testing.expect((divFloor(i32, -5, 3) catch unreachable) == -2);
try testing.expectError(error.DivisionByZero, divFloor(i8, -5, 0));
try testing.expectError(error.Overflow, divFloor(i8, -128, -1));
try testing.expect((divFloor(f32, 5.0, 3.0) catch unreachable) == 1.0);
try testing.expect((divFloor(f32, -5.0, 3.0) catch unreachable) == -2.0);
}
/// 计算 numerator 除以 denominator,向正无穷舍入。
/// 溢出或 denominator 为零时返回错误。
///
pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and numerator == minInt(T) and denominator == -1) {
return error.Overflow;
}
return @divCeil(numerator, denominator);
}
test divCeil {
try testDivCeil();
try comptime testDivCeil();
}
fn testDivCeil() !void {
try testing.expectEqual(@as(i32, 2), divCeil(i32, 5, 3) catch unreachable);
try testing.expectEqual(@as(i32, -1), divCeil(i32, -5, 3) catch unreachable);
try testing.expectEqual(@as(i32, -1), divCeil(i32, 5, -3) catch unreachable);
try testing.expectEqual(@as(i32, 2), divCeil(i32, -5, -3) catch unreachable);
try testing.expectEqual(@as(i32, 0), divCeil(i32, 0, 5) catch unreachable);
try testing.expectEqual(@as(u32, 0), divCeil(u32, 0, 5) catch unreachable);
try testing.expectError(error.DivisionByZero, divCeil(i8, -5, 0));
try testing.expectError(error.Overflow, divCeil(i8, -128, -1));
try testing.expectEqual(@as(f32, 0.0), divCeil(f32, 0.0, 5.0) catch unreachable);
try testing.expectEqual(@as(f32, 2.0), divCeil(f32, 5.0, 3.0) catch unreachable);
try testing.expectEqual(@as(f32, -1.0), divCeil(f32, -5.0, 3.0) catch unreachable);
try testing.expectEqual(@as(f32, -1.0), divCeil(f32, 5.0, -3.0) catch unreachable);
try testing.expectEqual(@as(f32, 2.0), divCeil(f32, -5.0, -3.0) catch unreachable);
try testing.expectEqual(6, divCeil(comptime_int, 23, 4) catch unreachable);
try testing.expectEqual(-5, divCeil(comptime_int, -23, 4) catch unreachable);
try testing.expectEqual(-5, divCeil(comptime_int, 23, -4) catch unreachable);
try testing.expectEqual(6, divCeil(comptime_int, -23, -4) catch unreachable);
try testing.expectError(error.DivisionByZero, divCeil(comptime_int, 23, 0));
try testing.expectEqual(6.0, divCeil(comptime_float, 23.0, 4.0) catch unreachable);
try testing.expectEqual(-5.0, divCeil(comptime_float, -23.0, 4.0) catch unreachable);
try testing.expectEqual(-5.0, divCeil(comptime_float, 23.0, -4.0) catch unreachable);
try testing.expectEqual(6.0, divCeil(comptime_float, -23.0, -4.0) catch unreachable);
try testing.expectError(error.DivisionByZero, divCeil(comptime_float, 23.0, 0.0));
}
/// 计算 numerator 除以 denominator。
/// 商不是整数、denominator 为零或发生溢出时返回错误。
pub fn divExact(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
const result = @divTrunc(numerator, denominator);
if (result * denominator != numerator) return error.UnexpectedRemainder;
return result;
}
test divExact {
try testDivExact();
try comptime testDivExact();
}
fn testDivExact() !void {
try testing.expect((divExact(i32, 10, 5) catch unreachable) == 2);
try testing.expect((divExact(i32, -10, 5) catch unreachable) == -2);
try testing.expectError(error.DivisionByZero, divExact(i8, -5, 0));
try testing.expectError(error.Overflow, divExact(i8, -128, -1));
try testing.expectError(error.UnexpectedRemainder, divExact(i32, 5, 2));
try testing.expect((divExact(f32, 10.0, 5.0) catch unreachable) == 2.0);
try testing.expect((divExact(f32, -10.0, 5.0) catch unreachable) == -2.0);
try testing.expectError(error.UnexpectedRemainder, divExact(f32, 5.0, 2.0));
}
/// 返回分子对分母取模的结果;若分母为零或
/// 负数则返回错误。分子为负时,返回值也
/// 不会为负。
pub fn mod(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (denominator < 0) return error.NegativeDenominator;
return @mod(numerator, denominator);
}
test mod {
try testMod();
try comptime testMod();
}
fn testMod() !void {
try testing.expect((mod(i32, -5, 3) catch unreachable) == 1);
try testing.expect((mod(i32, 5, 3) catch unreachable) == 2);
try testing.expectError(error.NegativeDenominator, mod(i32, 10, -1));
try testing.expectError(error.DivisionByZero, mod(i32, 10, 0));
try testing.expect((mod(f32, -5, 3) catch unreachable) == 1);
try testing.expect((mod(f32, 5, 3) catch unreachable) == 2);
try testing.expectError(error.NegativeDenominator, mod(f32, 10, -1));
try testing.expectError(error.DivisionByZero, mod(f32, 10, 0));
}
/// 返回 numerator 除以 denominator 的余数;若 denominator 为零或负数,则返回错误。负分子可能产生负结果。
///
///
pub fn rem(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;
if (denominator < 0) return error.NegativeDenominator;
return @rem(numerator, denominator);
}
test rem {
try testRem();
try comptime testRem();
}
fn testRem() !void {
try testing.expect((rem(i32, -5, 3) catch unreachable) == -2);
try testing.expect((rem(i32, 5, 3) catch unreachable) == 2);
try testing.expectError(error.NegativeDenominator, rem(i32, 10, -1));
try testing.expectError(error.DivisionByZero, rem(i32, 10, 0));
try testing.expect((rem(f32, -5, 3) catch unreachable) == -2);
try testing.expect((rem(f32, 5, 3) catch unreachable) == 2);
try testing.expectError(error.NegativeDenominator, rem(f32, 10, -1));
try testing.expectError(error.DivisionByZero, rem(f32, 10, 0));
}
/// 返回整数参数的相反数。
/// 结果为有符号整数。
pub fn negateCast(x: anytype) !@Int(.signed, @bitSizeOf(@TypeOf(x))) {
if (@typeInfo(@TypeOf(x)).int.signedness == .signed) return negate(x);
const int = @Int(.signed, @bitSizeOf(@TypeOf(x)));
if (x > -minInt(int)) return error.Overflow;
if (x == -minInt(int)) return minInt(int);
return -@as(int, @intCast(x));
}
test negateCast {
try testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999);
try testing.expect(@TypeOf(negateCast(@as(u32, 999)) catch unreachable) == i32);
try testing.expect((negateCast(@as(u32, -minInt(i32))) catch unreachable) == minInt(i32));
try testing.expect(@TypeOf(negateCast(@as(u32, -minInt(i32))) catch unreachable) == i32);
try testing.expectError(error.Overflow, negateCast(@as(u32, maxInt(i32) + 10)));
}
/// 将整数转换为另一整数类型。
/// 若值无法表示,则返回 null。
pub fn cast(comptime T: type, x: anytype) ?T {
comptime assert(@typeInfo(T) == .int); // 必须传入整数
const is_comptime = @TypeOf(x) == comptime_int;
comptime assert(is_comptime or @typeInfo(@TypeOf(x)) == .int); // 必须传入整数
if ((is_comptime or maxInt(@TypeOf(x)) > maxInt(T)) and x > maxInt(T)) {
return null;
} else if ((is_comptime or minInt(@TypeOf(x)) < minInt(T)) and x < minInt(T)) {
return null;
} else {
return @as(T, @intCast(x));
}
}
test cast {
try testing.expect(cast(u8, 300) == null);
try testing.expect(cast(u8, @as(u32, 300)) == null);
try testing.expect(cast(i8, -200) == null);
try testing.expect(cast(i8, @as(i32, -200)) == null);
try testing.expect(cast(u8, -1) == null);
try testing.expect(cast(u8, @as(i8, -1)) == null);
try testing.expect(cast(u64, -1) == null);
try testing.expect(cast(u64, @as(i8, -1)) == null);
try testing.expect(cast(u8, 255).? == @as(u8, 255));
try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255));
try testing.expect(@TypeOf(cast(u8, 255).?) == u8);
try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8);
}
pub const AlignCastError = error{UnalignedMemory};
fn AlignCastResult(comptime alignment: Alignment, comptime Ptr: type) type {
const orig = @typeInfo(Ptr).pointer;
return @Pointer(orig.size, .{
.@"const" = orig.is_const,
.@"volatile" = orig.is_volatile,
.@"allowzero" = orig.is_allowzero,
.@"align" = alignment.toByteUnits(),
.@"addrspace" = orig.address_space,
}, orig.child, orig.sentinel());
}
/// 对指针进行对齐转换,但对齐不正确时返回错误。
pub fn alignCast(comptime alignment: Alignment, ptr: anytype) AlignCastError!AlignCastResult(alignment, @TypeOf(ptr)) {
if (alignment.check(@intFromPtr(ptr))) return @alignCast(ptr);
return error.UnalignedMemory;
}
/// 断言 `int > 0`。
pub fn isPowerOfTwo(int: anytype) bool {
assert(int > 0);
return (int & (int - 1)) == 0;
}
test isPowerOfTwo {
try testing.expect(isPowerOfTwo(@as(u8, 1)));
try testing.expect(isPowerOfTwo(2));
try testing.expect(!isPowerOfTwo(@as(i16, 3)));
try testing.expect(isPowerOfTwo(4));
try testing.expect(!isPowerOfTwo(@as(u32, 31)));
try testing.expect(isPowerOfTwo(32));
try testing.expect(!isPowerOfTwo(@as(i64, 63)));
try testing.expect(isPowerOfTwo(128));
try testing.expect(isPowerOfTwo(@as(u128, 256)));
}
/// 将给定整数类型的位宽对齐到可被 8 整除的位宽。
pub fn ByteAlignedInt(comptime T: type) type {
const info = @typeInfo(T).int;
const bits = (info.bits + 7) / 8 * 8;
return @Int(info.signedness, bits);
}
test ByteAlignedInt {
try testing.expect(ByteAlignedInt(u0) == u0);
try testing.expect(ByteAlignedInt(u3) == u8);
try testing.expect(ByteAlignedInt(u8) == u8);
try testing.expect(ByteAlignedInt(i111) == i112);
try testing.expect(ByteAlignedInt(u129) == u136);
}
/// 将给定浮点数舍入到最近整数。
/// 如果两个整数距离相同,则远离零舍入。
/// 若可用,则使用专用硬件指令。
/// 等同于调用内置函数 @round。
pub inline fn round(value: anytype) @TypeOf(value) {
return @round(value);
}
/// 将给定浮点数向零舍入为整数。
/// 若可用,则使用专门的硬件指令。
/// 与调用内置函数 @trunc 相同。
pub inline fn trunc(value: anytype) @TypeOf(value) {
return @trunc(value);
}
/// 返回不大于给定浮点数的最大整数值。
/// 若可用,则使用专门的硬件指令。
/// 与调用内置函数 @floor 相同。
pub inline fn floor(value: anytype) @TypeOf(value) {
return @floor(value);
}
/// 返回小于或等于给定值的最大 2 的幂;
/// 如果给定值小于或等于零,则返回零。
pub fn floorPowerOfTwo(comptime T: type, value: T) T {
const uT = @Int(.unsigned, @typeInfo(T).int.bits);
if (value <= 0) return 0;
return @as(T, 1) << log2_int(uT, @as(uT, @intCast(value)));
}
test floorPowerOfTwo {
try testFloorPowerOfTwo();
try comptime testFloorPowerOfTwo();
}
fn testFloorPowerOfTwo() !void {
try testing.expect(floorPowerOfTwo(u32, 63) == 32);
try testing.expect(floorPowerOfTwo(u32, 64) == 64);
try testing.expect(floorPowerOfTwo(u32, 65) == 64);
try testing.expect(floorPowerOfTwo(u32, 0) == 0);
try testing.expect(floorPowerOfTwo(u4, 7) == 4);
try testing.expect(floorPowerOfTwo(u4, 8) == 8);
try testing.expect(floorPowerOfTwo(u4, 9) == 8);
try testing.expect(floorPowerOfTwo(u4, 0) == 0);
try testing.expect(floorPowerOfTwo(i4, 7) == 4);
try testing.expect(floorPowerOfTwo(i4, -8) == 0);
try testing.expect(floorPowerOfTwo(i4, -1) == 0);
try testing.expect(floorPowerOfTwo(i4, 0) == 0);
}
/// 返回不小于给定浮点数的最小整数值。
/// 若存在专用硬件指令,则使用该指令。
/// 等价于调用内置函数 @ceil。
pub inline fn ceil(value: anytype) @TypeOf(value) {
return @ceil(value);
}
/// 返回下一个二的幂;若值本身已是二的幂,则保持不变。
/// 仅可使用无符号整数。不允许输入零。
/// 结果类型比输入类型多 1 位。
pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) @Int(@typeInfo(T).int.signedness, @typeInfo(T).int.bits + 1) {
comptime assert(@typeInfo(T) == .int);
comptime assert(@typeInfo(T).int.signedness == .unsigned);
assert(value != 0);
const PromotedType = @Int(@typeInfo(T).int.signedness, @typeInfo(T).int.bits + 1);
const ShiftType = std.math.Log2Int(PromotedType);
return @as(PromotedType, 1) << @as(ShiftType, @intCast(@typeInfo(T).int.bits - @clz(value - 1)));
}
/// 返回下一个 2 的幂;若值已是 2 的幂,则返回原值。
/// 仅能使用无符号整数。不允许输入零。
/// 若结果无法表示,则返回错误。
pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
comptime assert(@typeInfo(T) == .int);
const info = @typeInfo(T).int;
comptime assert(info.signedness == .unsigned);
const PromotedType = @Int(info.signedness, info.bits + 1);
const overflowBit = @as(PromotedType, 1) << info.bits;
const x = ceilPowerOfTwoPromote(T, value);
if (overflowBit & x != 0) {
return error.Overflow;
}
return @as(T, @intCast(x));
}
/// 返回下一个 2 的幂(若该值已是 2 的幂,则原样返回)。
/// 仅可使用无符号整数。不允许输入零。
/// 断言结果能放入该类型。
pub fn ceilPowerOfTwoAssert(comptime T: type, value: T) T {
return ceilPowerOfTwo(T, value) catch unreachable;
}
test ceilPowerOfTwoPromote {
try testCeilPowerOfTwoPromote();
try comptime testCeilPowerOfTwoPromote();
}
fn testCeilPowerOfTwoPromote() !void {
try testing.expectEqual(@as(u33, 1), ceilPowerOfTwoPromote(u32, 1));
try testing.expectEqual(@as(u33, 2), ceilPowerOfTwoPromote(u32, 2));
try testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 63));
try testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 64));
try testing.expectEqual(@as(u33, 128), ceilPowerOfTwoPromote(u32, 65));
try testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 7));
try testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 8));
try testing.expectEqual(@as(u6, 16), ceilPowerOfTwoPromote(u5, 9));
try testing.expectEqual(@as(u5, 16), ceilPowerOfTwoPromote(u4, 9));
}
test ceilPowerOfTwo {
try testCeilPowerOfTwo();
try comptime testCeilPowerOfTwo();
}
fn testCeilPowerOfTwo() !void {
try testing.expectEqual(@as(u32, 1), try ceilPowerOfTwo(u32, 1));
try testing.expectEqual(@as(u32, 2), try ceilPowerOfTwo(u32, 2));
try testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 63));
try testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 64));
try testing.expectEqual(@as(u32, 128), try ceilPowerOfTwo(u32, 65));
try testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 7));
try testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 8));
try testing.expectEqual(@as(u5, 16), try ceilPowerOfTwo(u5, 9));
try testing.expectError(error.Overflow, ceilPowerOfTwo(u4, 9));
}
/// 返回整数值 x 以 2 为底的对数,
/// 向下舍入到最近整数。
pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
if (@typeInfo(T) != .int or @typeInfo(T).int.signedness != .unsigned)
@compileError("log2_int requires an unsigned integer, found " ++ @typeName(T));
assert(x != 0);
return @as(Log2Int(T), @intCast(@typeInfo(T).int.bits - 1 - @clz(x)));
}
test log2_int {
try testing.expect(log2_int(u32, 1) == 0);
try testing.expect(log2_int(u32, 2) == 1);
try testing.expect(log2_int(u32, 3) == 1);
try testing.expect(log2_int(u32, 4) == 2);
try testing.expect(log2_int(u32, 5) == 2);
try testing.expect(log2_int(u32, 6) == 2);
try testing.expect(log2_int(u32, 7) == 2);
try testing.expect(log2_int(u32, 8) == 3);
try testing.expect(log2_int(u32, 9) == 3);
try testing.expect(log2_int(u32, 10) == 3);
}
/// 返回整数值 x 以 2 为底的对数,
/// 向上舍入到最近整数。
pub fn log2_int_ceil(comptime T: type, x: T) Log2IntCeil(T) {
if (@typeInfo(T) != .int or @typeInfo(T).int.signedness != .unsigned)
@compileError("log2_int_ceil requires an unsigned integer, found " ++ @typeName(T));
assert(x != 0);
if (x == 1) return 0;
const log2_val: Log2IntCeil(T) = log2_int(T, x - 1);
return log2_val + 1;
}
test log2_int_ceil {
try testing.expect(log2_int_ceil(u32, 1) == 0);
try testing.expect(log2_int_ceil(u32, 2) == 1);
try testing.expect(log2_int_ceil(u32, 3) == 2);
try testing.expect(log2_int_ceil(u32, 4) == 2);
try testing.expect(log2_int_ceil(u32, 5) == 3);
try testing.expect(log2_int_ceil(u32, 6) == 3);
try testing.expect(log2_int_ceil(u32, 7) == 3);
try testing.expect(log2_int_ceil(u32, 8) == 3);
try testing.expect(log2_int_ceil(u32, 9) == 4);
try testing.expect(log2_int_ceil(u32, 10) == 4);
}
/// 将值转换为另一类型。若该值超出新类型的范围,
/// 或无法由新类型精确表示,则转换为
/// 最接近的可表示值。
pub fn lossyCast(comptime T: type, value: anytype) T {
switch (@typeInfo(T)) {
.float => {
switch (@typeInfo(@TypeOf(value))) {
.int => return @floatFromInt(value),
.float => return @floatCast(value),
.comptime_int => return value,
.comptime_float => return value,
else => @compileError("bad type"),
}
},
.int => {
switch (@typeInfo(@TypeOf(value))) {
.int, .comptime_int => {
if (value >= maxInt(T)) {
return maxInt(T);
} else if (value <= minInt(T)) {
return minInt(T);
} else {
return @intCast(value);
}
},
.float, .comptime_float => {
// 极端情况下,可能需要增强语言,允许在此处
// 指定舍入模式,以防止 `@intFromFloat` 触发 panic。
const max: @TypeOf(value) = @floatFromInt(maxInt(T));
const min: @TypeOf(value) = @floatFromInt(minInt(T));
if (isNan(value)) {
return 0;
} else if (value >= max) {
return maxInt(T);
} else if (value <= min) {
return minInt(T);
} else {
return @intFromFloat(value);
}
},
else => @compileError("bad type"),
}
},
else => @compileError("bad result type"),
}
}
test lossyCast {
try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));
try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));
try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));
try testing.expect(lossyCast(u32, @as(f32, @floatFromInt(maxInt(u32)))) == maxInt(u32));
try testing.expect(lossyCast(u32, nan(f32)) == 0);
}
/// 根据 *t* 在 *a* 与 *b* 之间进行线性插值。
/// *t* 的范围通常为 0.0 到 1.0,但也可能超出此范围。
/// 支持浮点数和浮点数向量。
///
/// 由于浮点误差,*t* 为 1 时不保证返回 *b*。
/// 此函数具有单调性。
pub fn lerp(a: anytype, b: anytype, t: anytype) @TypeOf(a, b, t) {
const Type = @TypeOf(a, b, t);
return @mulAdd(Type, b - a, t, a);
}
test lerp {
if (builtin.zig_backend == .stage2_c and builtin.cpu.arch.isArm()) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_c and builtin.cpu.arch.isX86()) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_x86_64 and !comptime builtin.cpu.has(.x86, .fma)) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/17884
try testing.expectEqual(@as(f64, 75), lerp(50, 100, 0.5));
try testing.expectEqual(@as(f32, 43.75), lerp(50, 25, 0.25));
try testing.expectEqual(@as(f64, -31.25), lerp(-50, 25, 0.25));
try testing.expectEqual(@as(f64, 30), lerp(10, 20, 2.0));
try testing.expectEqual(@as(f64, 5), lerp(10, 20, -0.5));
try testing.expectApproxEqRel(@as(f32, -7.16067345e+03), lerp(-10000.12345, -5000.12345, 0.56789), 1e-19);
try testing.expectApproxEqRel(@as(f64, 7.010987590521e+62), lerp(0.123456789e-64, 0.123456789e64, 0.56789), 1e-33);
try testing.expectEqual(@as(f32, 0.0), lerp(@as(f32, 1.0e8), 1.0, 1.0));
try testing.expectEqual(@as(f64, 0.0), lerp(@as(f64, 1.0e16), 1.0, 1.0));
try testing.expectEqual(@as(f32, 1.0), lerp(@as(f32, 1.0e7), 1.0, 1.0));
try testing.expectEqual(@as(f64, 1.0), lerp(@as(f64, 1.0e15), 1.0, 1.0));
{
const a: @Vector(3, f32) = @splat(0);
const b: @Vector(3, f32) = @splat(50);
const t: @Vector(3, f32) = @splat(0.5);
try testing.expectEqual(
@Vector(3, f32){ 25, 25, 25 },
lerp(a, b, t),
);
}
{
const a: @Vector(3, f64) = @splat(50);
const b: @Vector(3, f64) = @splat(100);
const t: @Vector(3, f64) = @splat(0.5);
try testing.expectEqual(
@Vector(3, f64){ 75, 75, 75 },
lerp(a, b, t),
);
}
{
const a: @Vector(2, f32) = @splat(40);
const b: @Vector(2, f32) = @splat(80);
const t: @Vector(2, f32) = @Vector(2, f32){ 0.25, 0.75 };
try testing.expectEqual(
@Vector(2, f32){ 50, 70 },
lerp(a, b, t),
);
}
}
/// 返回整数类型 T 的最大值。
pub fn maxInt(comptime T: type) comptime_int {
const info = @typeInfo(T).int;
return (1 << (info.bits - @intFromBool(info.signedness == .signed))) - 1;
}
/// 返回整数类型 T 的最小值。
pub fn minInt(comptime T: type) comptime_int {
const info = @typeInfo(T).int;
return switch (info.signedness) {
.unsigned => 0,
.signed => -(1 << (info.bits - 1)),
};
}
test maxInt {
try testing.expect(maxInt(u0) == 0);
try testing.expect(maxInt(u1) == 1);
try testing.expect(maxInt(u8) == 255);
try testing.expect(maxInt(u16) == 65535);
try testing.expect(maxInt(u32) == 4294967295);
try testing.expect(maxInt(u64) == 18446744073709551615);
try testing.expect(maxInt(u128) == 340282366920938463463374607431768211455);
try testing.expect(maxInt(i1) == 0);
try testing.expect(maxInt(i8) == 127);
try testing.expect(maxInt(i16) == 32767);
try testing.expect(maxInt(i32) == 2147483647);
try testing.expect(maxInt(i63) == 4611686018427387903);
try testing.expect(maxInt(i64) == 9223372036854775807);
try testing.expect(maxInt(i128) == 170141183460469231731687303715884105727);
}
test minInt {
try testing.expect(minInt(u0) == 0);
try testing.expect(minInt(u1) == 0);
try testing.expect(minInt(u8) == 0);
try testing.expect(minInt(u16) == 0);
try testing.expect(minInt(u32) == 0);
try testing.expect(minInt(u63) == 0);
try testing.expect(minInt(u64) == 0);
try testing.expect(minInt(u128) == 0);
try testing.expect(minInt(i1) == -1);
try testing.expect(minInt(i8) == -128);
try testing.expect(minInt(i16) == -32768);
try testing.expect(minInt(i32) == -2147483648);
try testing.expect(minInt(i63) == -4611686018427387904);
try testing.expect(minInt(i64) == -9223372036854775808);
try testing.expect(minInt(i128) == -170141183460469231731687303715884105728);
}
test "max value type" {
const x: u32 = maxInt(i32);
try testing.expect(x == 2147483647);
}
/// 计算 a 和 b 的乘积。返回类型足够宽,保证不会溢出。
///
pub fn mulWide(comptime T: type, a: T, b: T) @Int(
@typeInfo(T).int.signedness,
@typeInfo(T).int.bits * 2,
) {
const ResultInt = @Int(
@typeInfo(T).int.signedness,
@typeInfo(T).int.bits * 2,
);
return @as(ResultInt, a) * @as(ResultInt, b);
}
test mulWide {
try testing.expect(mulWide(u8, 5, 5) == 25);
try testing.expect(mulWide(i8, 5, -5) == -25);
try testing.expect(mulWide(u8, 100, 100) == 10000);
}
/// 另见 `CompareOperator`。
pub const Order = enum {
/// 大于(`>`)
gt,
/// 小于(`<`)
lt,
/// 等于(`==`)
eq,
pub fn invert(self: Order) Order {
return switch (self) {
.lt => .gt,
.eq => .eq,
.gt => .lt,
};
}
test invert {
try testing.expect(Order.invert(order(0, 0)) == .eq);
try testing.expect(Order.invert(order(1, 0)) == .lt);
try testing.expect(Order.invert(order(-1, 0)) == .gt);
}
pub fn differ(self: Order) ?Order {
return if (self != .eq) self else null;
}
test differ {
const neg: i32 = -1;
const zero: i32 = 0;
const pos: i32 = 1;
try testing.expect(order(zero, neg).differ() orelse
order(pos, zero) == .gt);
try testing.expect(order(zero, zero).differ() orelse
order(zero, zero) == .eq);
try testing.expect(order(pos, pos).differ() orelse
order(neg, zero) == .lt);
try testing.expect(order(zero, zero).differ() orelse
order(pos, neg).differ() orelse
order(neg, zero) == .gt);
try testing.expect(order(pos, pos).differ() orelse
order(pos, pos).differ() orelse
order(neg, neg) == .eq);
try testing.expect(order(zero, pos).differ() orelse
order(neg, pos).differ() orelse
order(pos, neg) == .lt);
}
pub fn compare(self: Order, op: CompareOperator) bool {
return switch (self) {
.lt => switch (op) {
.lt => true,
.lte => true,
.eq => false,
.gte => false,
.gt => false,
.neq => true,
},
.eq => switch (op) {
.lt => false,
.lte => true,
.eq => true,
.gte => true,
.gt => false,
.neq => false,
},
.gt => switch (op) {
.lt => false,
.lte => false,
.eq => false,
.gte => true,
.gt => true,
.neq => true,
},
};
}
// https://github.com/ziglang/zig/issues/19295
test "compare" {
try testing.expect(order(-1, 0).compare(.lt));
try testing.expect(order(-1, 0).compare(.lte));
try testing.expect(order(0, 0).compare(.lte));
try testing.expect(order(0, 0).compare(.eq));
try testing.expect(order(0, 0).compare(.gte));
try testing.expect(order(1, 0).compare(.gte));
try testing.expect(order(1, 0).compare(.gt));
try testing.expect(order(1, 0).compare(.neq));
}
};
/// 给定两个数,返回它们彼此的大小关系。
pub fn order(a: anytype, b: anytype) Order {
if (a == b) {
return .eq;
} else if (a < b) {
return .lt;
} else if (a > b) {
return .gt;
} else {
unreachable;
}
}
/// 另请参见 `Order`。
pub const CompareOperator = enum {
/// 小于(`<`)
lt,
/// 小于或等于(`<=`)
lte,
/// 等于(`==`)
eq,
/// 大于或等于(`>=`)
gte,
/// 大于(`>`)
gt,
/// 不相等(`!=`)
neq,
/// 反转比较方向。
/// 交换左右操作数时使用。
pub fn reverse(op: CompareOperator) CompareOperator {
return switch (op) {
.lt => .gt,
.lte => .gte,
.gt => .lt,
.gte => .lte,
.eq => .eq,
.neq => .neq,
};
}
test reverse {
inline for (@typeInfo(CompareOperator).@"enum".field_values) |op_field_value| {
const op = @as(CompareOperator, @fromBackingInt(@intCast(op_field_value)));
try testing.expect(compare(2, op, 3) == compare(3, op.reverse(), 2));
try testing.expect(compare(3, op, 3) == compare(3, op.reverse(), 3));
try testing.expect(compare(4, op, 3) == compare(3, op.reverse(), 4));
}
}
};
/// 此函数与比较运算符执行相同操作,但运算符
/// 是运行时已知的枚举值。适用于支持
/// 比较运算符的任意操作数。
pub fn compare(a: anytype, op: CompareOperator, b: anytype) bool {
return switch (op) {
.lt => a < b,
.lte => a <= b,
.eq => a == b,
.neq => a != b,
.gt => a > b,
.gte => a >= b,
};
}
test compare {
try testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255)));
try testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1)));
try testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255)));
try testing.expect(compare(@as(u8, 255), .gt, @as(i8, -1)));
try testing.expect(!compare(@as(u8, 255), .lte, @as(i8, -1)));
try testing.expect(compare(@as(i8, -1), .lt, @as(u9, 255)));
try testing.expect(!compare(@as(i8, -1), .gte, @as(u9, 255)));
try testing.expect(compare(@as(u9, 255), .gt, @as(i8, -1)));
try testing.expect(!compare(@as(u9, 255), .lte, @as(i8, -1)));
try testing.expect(compare(@as(i9, -1), .lt, @as(u8, 255)));
try testing.expect(!compare(@as(i9, -1), .gte, @as(u8, 255)));
try testing.expect(compare(@as(u8, 255), .gt, @as(i9, -1)));
try testing.expect(!compare(@as(u8, 255), .lte, @as(i9, -1)));
try testing.expect(compare(@as(u8, 1), .lt, @as(u8, 2)));
try testing.expect(@as(u8, @bitCast(@as(i8, -1))) == @as(u8, 255));
try testing.expect(!compare(@as(u8, 255), .eq, @as(i8, -1)));
try testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1)));
}
test order {
try testing.expect(order(0, 0) == .eq);
try testing.expect(order(1, 0) == .gt);
try testing.expect(order(-1, 0) == .lt);
}
/// 值为 true 时返回全一掩码,为 false 时返回全零掩码。
/// 对于寄存器大小的整数,会编译为一条指令。
///
pub inline fn boolMask(comptime MaskInt: type, value: bool) MaskInt {
if (@typeInfo(MaskInt) != .int)
@compileError("boolMask requires an integer mask type.");
if (MaskInt == u0)
@compileError("boolMask cannot convert to u0, it is too small.");
// u1 和 i1 情况容易溢出,
// 因此在此特殊处理。
if (MaskInt == u1) return @intFromBool(value);
if (MaskInt == i1) {
// 此处 @as 用于规避 #7950
return @as(i1, @bitCast(@as(u1, @intFromBool(value))));
}
return -%@as(MaskInt, @intCast(@intFromBool(value)));
}
test boolMask {
const runTest = struct {
fn runTest() !void {
try testing.expectEqual(@as(u1, 0), boolMask(u1, false));
try testing.expectEqual(@as(u1, 1), boolMask(u1, true));
try testing.expectEqual(@as(i1, 0), boolMask(i1, false));
try testing.expectEqual(@as(i1, -1), boolMask(i1, true));
try testing.expectEqual(@as(u13, 0), boolMask(u13, false));
try testing.expectEqual(@as(u13, 0x1FFF), boolMask(u13, true));
try testing.expectEqual(@as(i13, 0), boolMask(i13, false));
try testing.expectEqual(@as(i13, -1), boolMask(i13, true));
try testing.expectEqual(@as(u32, 0), boolMask(u32, false));
try testing.expectEqual(@as(u32, 0xFFFF_FFFF), boolMask(u32, true));
try testing.expectEqual(@as(i32, 0), boolMask(i32, false));
try testing.expectEqual(@as(i32, -1), boolMask(i32, true));
}
}.runTest;
try runTest();
try comptime runTest();
}
/// 使用最小整数类型返回 `num` 的模
pub fn comptimeMod(num: anytype, comptime denom: comptime_int) IntFittingRange(0, denom - 1) {
return @as(IntFittingRange(0, denom - 1), @intCast(@mod(num, denom)));
}
pub const F80 = struct {
fraction: u64,
exp: u16,
pub fn toFloat(self: F80) f80 {
const int = (@as(u80, self.exp) << 64) | self.fraction;
return @as(f80, @bitCast(int));
}
pub fn fromFloat(x: f80) F80 {
const int = @as(u80, @bitCast(x));
return .{
.fraction = @as(u64, @truncate(int)),
.exp = @as(u16, @truncate(int >> 64)),
};
}
};
fn SignOf(T: type) type {
return switch (@typeInfo(T)) {
.comptime_int, .comptime_float => comptime_int,
.int => IntFittingRange(@max(minInt(T), -1), @min(maxInt(T), 1)),
.float => IntFittingRange(-1, 1),
.vector => |vec| @Vector(vec.len, SignOf(vec.child)),
else => @compileError("Expected an int, float, or a vector of one, found " ++ @typeName(T)),
};
}
/// 返回 -1、0 或 1。
/// 支持整数和浮点数类型,以及整数和浮点数向量。
/// 无符号整数类型始终返回 0 或 1。
/// 返回整数类型是足以容纳所有可能值的最小类型。
/// 无分支。
pub inline fn sign(n: anytype) SignOf(@TypeOf(n)) {
const T = SignOf(@TypeOf(n));
const zero: T = if (@typeInfo(T) == .vector) @splat(0) else 0;
const pos: T = @intCast(@intFromBool(n > zero));
const neg: T = @intCast(@intFromBool(n < zero));
return pos - neg;
}
fn testSign() !void {
// 以下每个代码块均检查输入:
// 2, -2, 0, { 2, -2, 0 } 提供预期输出;
// 1, -1, 0, { 1, -1, 0 } 对应给定的 T。
// (无符号类型省略负值。)
{
const T = i8;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 }));
}
{
const T = i32;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 }));
}
{
const T = i64;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 }));
}
{
const T = u8;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(2, T){ 1, 0 }, sign(@Vector(2, T){ 2, 0 }));
}
{
const T = u32;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(2, T){ 1, 0 }, sign(@Vector(2, T){ 2, 0 }));
}
{
const T = u64;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(2, T){ 1, 0 }, sign(@Vector(2, T){ 2, 0 }));
}
{
const T = f16;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 }));
}
{
const T = f32;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 }));
}
{
const T = f64;
try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2)));
try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2)));
try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0)));
try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 }));
}
// comptime_int
try std.testing.expectEqual(-1, sign(-10));
try std.testing.expectEqual(1, sign(10));
try std.testing.expectEqual(0, sign(0));
// comptime_float
try std.testing.expectEqual(-1.0, sign(-10.0));
try std.testing.expectEqual(1.0, sign(10.0));
try std.testing.expectEqual(0.0, sign(0.0));
}
test sign {
try testSign();
try comptime testSign();
}
/// 通过复制最高有效位增大整数的位宽。
/// 当按二进制补码整数解释时,
/// 输入与输出具有相同的算术值。
pub fn signExtend(To: type, n: anytype) To {
const From = @TypeOf(n);
if (From == u0) return 0;
const FromSigned = @Int(.signed, @typeInfo(From).int.bits);
const ToSigned = @Int(.signed, @typeInfo(To).int.bits);
return @bitCast(@as(ToSigned, @as(FromSigned, @bitCast(n))));
}
test signExtend {
const number: u8 = 0x86;
try testing.expectEqual(0xff86, signExtend(u16, number));
try testing.expectEqual(0, signExtend(u1, @as(u0, 0)));
try testing.expectEqual(0, signExtend(u16, @as(u0, 0)));
try testing.expectEqual(0x0000, signExtend(u16, @as(u1, 0b0)));
try testing.expectEqual(0xffff, signExtend(u16, @as(u1, 0b1)));
try testing.expectEqual(0b000, signExtend(u3, @as(u2, 0b00)));
try testing.expectEqual(0b001, signExtend(u3, @as(u2, 0b01)));
try testing.expectEqual(0b110, signExtend(u3, @as(u2, 0b10)));
try testing.expectEqual(0b111, signExtend(u3, @as(u2, 0b11)));
try testing.expectEqual(0b0000_0001, signExtend(u8, @as(u2, 0b01)));
try testing.expectEqual(0b1111_1110, signExtend(u8, @as(u2, 0b10)));
try testing.expectEqual(0x0039, signExtend(u16, @as(u8, 0x39)));
try testing.expectEqual(0xff93, signExtend(u16, @as(u8, 0x93)));
try testing.expectEqual(5, signExtend(i32, @as(i8, 5)));
try testing.expectEqual(-123, signExtend(i16, @as(i8, -123)));
}