authorgravatar for nathan@nmichaels.orgNathan Michaels <nathan@nmichaels.org> 2021-09-30 00:10:25-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-10-02 16:06:03-04:00
log4916e26be434309209585a7c8a7918ed58c79466
treeefbb41dd160bd766131a932fa133dd0f97a670d4
parent468ed7ada50c743eabe01b36d0ee9f090d80e00a

Document some functions in std.math.


1 files changed, 72 insertions(+), 16 deletions(-)

lib/std/math.zig+72-16
......@@ -277,6 +277,8 @@ test {
277277 std.testing.refAllDecls(@This());
278278}
279279
280/// Returns the number of bits in the mantissa of floating point type
281/// T.
280282pub fn floatMantissaBits(comptime T: type) comptime_int {
281283 assert(@typeInfo(T) == .Float);
282284
......@@ -290,6 +292,8 @@ pub fn floatMantissaBits(comptime T: type) comptime_int {
290292 };
291293}
292294
295/// Returns the number of bits in the exponent of floating point type
296/// T.
293297pub fn floatExponentBits(comptime T: type) comptime_int {
294298 assert(@typeInfo(T) == .Float);
295299
......@@ -322,20 +326,22 @@ pub fn Min(comptime A: type, comptime B: type) type {
322326 return @TypeOf(@as(A, 0) + @as(B, 0));
323327}
324328
325/// Returns the smaller number. When one of the parameter's type's full range fits in the other,
326/// the return type is the smaller type.
329/// Returns the smaller number. When one parameter's type's full range
330/// fits in the other, the return type is the smaller type.
327331pub fn min(x: anytype, y: anytype) Min(@TypeOf(x), @TypeOf(y)) {
328332 const Result = Min(@TypeOf(x), @TypeOf(y));
329333 if (x < y) {
330 // TODO Zig should allow this as an implicit cast because x is immutable and in this
331 // scope it is known to fit in the return type.
334 // TODO Zig should allow this as an implicit cast because x is
335 // immutable and in this scope it is known to fit in the
336 // return type.
332337 switch (@typeInfo(Result)) {
333338 .Int => return @intCast(Result, x),
334339 else => return x,
335340 }
336341 } else {
337 // TODO Zig should allow this as an implicit cast because y is immutable and in this
338 // scope it is known to fit in the return type.
342 // TODO Zig should allow this as an implicit cast because y is
343 // immutable and in this scope it is known to fit in the
344 // return type.
339345 switch (@typeInfo(Result)) {
340346 .Int => return @intCast(Result, y),
341347 else => return y,
......@@ -375,7 +381,7 @@ test "math.min" {
375381 }
376382}
377383
378/// Finds the min of three numbers
384/// Finds the minimum of three numbers.
379385pub fn min3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) {
380386 return min(x, min(y, z));
381387}
......@@ -389,6 +395,8 @@ test "math.min3" {
389395 try testing.expect(min3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 0);
390396}
391397
398/// Returns the maximum of two numbers. Return type is the one with the
399/// larger range.
392400pub fn max(x: anytype, y: anytype) @TypeOf(x, y) {
393401 return if (x > y) x else y;
394402}
......@@ -398,7 +406,7 @@ test "math.max" {
398406 try testing.expect(max(@as(i32, 2), @as(i32, -1)) == 2);
399407}
400408
401/// Finds the max of three numbers
409/// Finds the maximum of three numbers.
402410pub fn max3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) {
403411 return max(x, max(y, z));
404412}
......@@ -412,6 +420,7 @@ test "math.max3" {
412420 try testing.expect(max3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 2);
413421}
414422
423/// Limit val to the inclusive range [lower, upper].
415424pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
416425 assert(lower <= upper);
417426 return max(lower, min(val, upper));
......@@ -433,17 +442,20 @@ test "math.clamp" {
433442 try testing.expect(std.math.clamp(i, 0, 1) == 1);
434443}
435444
445/// Returns the product of a and b. Returns an error on overflow.
436446pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {
437447 var answer: T = undefined;
438448 return if (@mulWithOverflow(T, a, b, &answer)) error.Overflow else answer;
439449}
440450
451/// Returns the sum of a and b. Returns an error on overflow.
441452pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) {
442453 if (T == comptime_int) return a + b;
443454 var answer: T = undefined;
444455 return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer;
445456}
446457
458/// Returns a - b, or an error on overflow.
447459pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) {
448460 var answer: T = undefined;
449461 return if (@subWithOverflow(T, a, b, &answer)) error.Overflow else answer;
......@@ -453,6 +465,8 @@ pub fn negate(x: anytype) !@TypeOf(x) {
453465 return sub(@TypeOf(x), 0, x);
454466}
455467
468/// Shifts a left by shift_amt. Returns an error on overflow. shift_amt
469/// is unsigned.
456470pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T {
457471 var answer: T = undefined;
458472 return if (@shlWithOverflow(T, a, shift_amt, &answer)) error.Overflow else answer;
......@@ -538,8 +552,8 @@ test "math.shr" {
538552 try testing.expect(shr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, 33)[0] == 0);
539553}
540554
541/// Rotates right. Only unsigned values can be rotated.
542/// Negative shift values results in shift modulo the bit count.
555/// Rotates right. Only unsigned values can be rotated. Negative shift
556/// values result in shift modulo the bit count.
543557pub fn rotr(comptime T: type, x: T, r: anytype) T {
544558 if (@typeInfo(T) == .Vector) {
545559 const C = @typeInfo(T).Vector.child;
......@@ -566,8 +580,8 @@ test "math.rotr" {
566580 try testing.expect(rotr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){1}, @as(isize, -1))[0] == @as(u32, 1) << 1);
567581}
568582
569/// Rotates left. Only unsigned values can be rotated.
570/// Negative shift values results in shift modulo the bit count.
583/// Rotates left. Only unsigned values can be rotated. Negative shift
584/// values result in shift modulo the bit count.
571585pub fn rotl(comptime T: type, x: T, r: anytype) T {
572586 if (@typeInfo(T) == .Vector) {
573587 const C = @typeInfo(T).Vector.child;
......@@ -594,6 +608,8 @@ test "math.rotl" {
594608 try testing.expect(rotl(std.meta.Vector(1, u32), std.meta.Vector(1, u32){1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30);
595609}
596610
611/// Returns an unsigned int type that can hold the number of bits in T
612/// - 1. Suitable for 0-based bit indices of T.
597613pub fn Log2Int(comptime T: type) type {
598614 // comptime ceil log2
599615 comptime var count = 0;
......@@ -605,6 +621,7 @@ pub fn Log2Int(comptime T: type) type {
605621 return std.meta.Int(.unsigned, count);
606622}
607623
624/// Returns an unsigned int type that can hold the number of bits in T.
608625pub fn Log2IntCeil(comptime T: type) type {
609626 // comptime ceil log2
610627 comptime var count = 0;
......@@ -616,6 +633,7 @@ pub fn Log2IntCeil(comptime T: type) type {
616633 return std.meta.Int(.unsigned, count);
617634}
618635
636/// Returns the smallest integer type that can hold both from and to.
619637pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type {
620638 assert(from <= to);
621639 if (from == 0 and to == 0) {
......@@ -691,6 +709,8 @@ fn testOverflow() !void {
691709 try testing.expect((shlExact(i32, 0b11, 4) catch unreachable) == 0b110000);
692710}
693711
712/// Returns the absolute value of x, where x is a value of an integer
713/// type.
694714pub fn absInt(x: anytype) !@TypeOf(x) {
695715 const T = @TypeOf(x);
696716 comptime assert(@typeInfo(T) == .Int); // must pass an integer to absInt
......@@ -724,6 +744,8 @@ fn testAbsFloat() !void {
724744 try testing.expect(absFloat(@as(f32, 10.05)) == 10.05);
725745}
726746
747/// Divide numerator by denominator, rounding toward zero. Returns an
748/// error on overflow or when denominator is zero.
727749pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T {
728750 @setRuntimeSafety(false);
729751 if (denominator == 0) return error.DivisionByZero;
......@@ -745,6 +767,9 @@ fn testDivTrunc() !void {
745767 try testing.expect((divTrunc(f32, -5.0, 3.0) catch unreachable) == -1.0);
746768}
747769
770/// Divide numerator by denominator, rounding toward negative
771/// infinity. Returns an error on overflow or when denominator is
772/// zero.
748773pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T {
749774 @setRuntimeSafety(false);
750775 if (denominator == 0) return error.DivisionByZero;
......@@ -766,6 +791,9 @@ fn testDivFloor() !void {
766791 try testing.expect((divFloor(f32, -5.0, 3.0) catch unreachable) == -2.0);
767792}
768793
794/// Divide numerator by denominator, rounding toward positive
795/// infinity. Returns an error on overflow or when denominator is
796/// zero.
769797pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T {
770798 @setRuntimeSafety(false);
771799 if (comptime std.meta.trait.isNumber(T) and denominator == 0) return error.DivisionByZero;
......@@ -819,6 +847,8 @@ fn testDivCeil() !void {
819847 try testing.expectError(error.DivisionByZero, divCeil(comptime_float, 23.0, 0.0));
820848}
821849
850/// Divide numerator by denominator. Return an error if quotient is
851/// not an integer, denominator is zero, or on overflow.
822852pub fn divExact(comptime T: type, numerator: T, denominator: T) !T {
823853 @setRuntimeSafety(false);
824854 if (denominator == 0) return error.DivisionByZero;
......@@ -844,6 +874,9 @@ fn testDivExact() !void {
844874 try testing.expectError(error.UnexpectedRemainder, divExact(f32, 5.0, 2.0));
845875}
846876
877/// Returns numerator modulo denominator, or an error if denominator is
878/// zero or negative. Negative numerators never result in negative
879/// return values.
847880pub fn mod(comptime T: type, numerator: T, denominator: T) !T {
848881 @setRuntimeSafety(false);
849882 if (denominator == 0) return error.DivisionByZero;
......@@ -867,6 +900,9 @@ fn testMod() !void {
867900 try testing.expectError(error.DivisionByZero, mod(f32, 10, 0));
868901}
869902
903/// Returns the remainder when numerator is divided by denominator, or
904/// an error if denominator is zero or negative. Negative numerators
905/// can give negative results.
870906pub fn rem(comptime T: type, numerator: T, denominator: T) !T {
871907 @setRuntimeSafety(false);
872908 if (denominator == 0) return error.DivisionByZero;
......@@ -989,6 +1025,8 @@ pub fn isPowerOfTwo(v: anytype) bool {
9891025 return (v & (v - 1)) == 0;
9901026}
9911027
1028/// Returns the nearest power of two less than or equal to value, or
1029/// zero if value is less than or equal to zero.
9921030pub fn floorPowerOfTwo(comptime T: type, value: T) T {
9931031 var x = value;
9941032
......@@ -1042,6 +1080,9 @@ pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
10421080 return @intCast(T, x);
10431081}
10441082
1083/// Returns the next power of two (if the value is not already a power
1084/// of two). Only unsigned integers can be used. Zero is not an
1085/// allowed input. Asserts that the value fits.
10451086pub fn ceilPowerOfTwoAssert(comptime T: type, value: T) T {
10461087 return ceilPowerOfTwo(T, value) catch unreachable;
10471088}
......@@ -1080,6 +1121,8 @@ fn testCeilPowerOfTwo() !void {
10801121 try testing.expectError(error.Overflow, ceilPowerOfTwo(u4, 9));
10811122}
10821123
1124/// Return the log base 2 of integer value x, rounding down to the
1125/// nearest integer.
10831126pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
10841127 if (@typeInfo(T) != .Int or @typeInfo(T).Int.signedness != .unsigned)
10851128 @compileError("log2_int requires an unsigned integer, found " ++ @typeName(T));
......@@ -1087,6 +1130,8 @@ pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
10871130 return @intCast(Log2Int(T), @typeInfo(T).Int.bits - 1 - @clz(T, x));
10881131}
10891132
1133/// Return the log base 2 of integer value x, rounding up to the
1134/// nearest integer.
10901135pub fn log2_int_ceil(comptime T: type, x: T) Log2IntCeil(T) {
10911136 if (@typeInfo(T) != .Int or @typeInfo(T).Int.signedness != .unsigned)
10921137 @compileError("log2_int_ceil requires an unsigned integer, found " ++ @typeName(T));
......@@ -1109,8 +1154,9 @@ test "std.math.log2_int_ceil" {
11091154 try testing.expect(log2_int_ceil(u32, 10) == 4);
11101155}
11111156
1112///Cast a value to a different type. If the value doesn't fit in, or can't be perfectly represented by,
1113///the new type, it will be converted to the closest possible representation.
1157/// Cast a value to a different type. If the value doesn't fit in, or
1158/// can't be perfectly represented by, the new type, it will be
1159/// converted to the closest possible representation.
11141160pub fn lossyCast(comptime T: type, value: anytype) T {
11151161 switch (@typeInfo(T)) {
11161162 .Float => {
......@@ -1161,6 +1207,7 @@ test "math.f64_min" {
11611207 try testing.expect(@bitCast(u64, fmin) == f64_min_u64);
11621208}
11631209
1210/// Returns the maximum value of integer type T.
11641211pub fn maxInt(comptime T: type) comptime_int {
11651212 const info = @typeInfo(T);
11661213 const bit_count = info.Int.bits;
......@@ -1168,6 +1215,7 @@ pub fn maxInt(comptime T: type) comptime_int {
11681215 return (1 << (bit_count - @boolToInt(info.Int.signedness == .signed))) - 1;
11691216}
11701217
1218/// Returns the minimum value of integer type T.
11711219pub fn minInt(comptime T: type) comptime_int {
11721220 const info = @typeInfo(T);
11731221 const bit_count = info.Int.bits;
......@@ -1218,8 +1266,16 @@ test "max value type" {
12181266 try testing.expect(x == 2147483647);
12191267}
12201268
1221pub fn mulWide(comptime T: type, a: T, b: T) std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits * 2) {
1222 const ResultInt = std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits * 2);
1269/// Multiply a and b. Return type is wide enough to guarantee no
1270/// overflow.
1271pub fn mulWide(comptime T: type, a: T, b: T) std.meta.Int(
1272 @typeInfo(T).Int.signedness,
1273 @typeInfo(T).Int.bits * 2,
1274) {
1275 const ResultInt = std.meta.Int(
1276 @typeInfo(T).Int.signedness,
1277 @typeInfo(T).Int.bits * 2,
1278 );
12231279 return @as(ResultInt, a) * @as(ResultInt, b);
12241280}
12251281