aboutsummaryrefslogtreecommitdiff
path: root/lib/std/math.zig
diff options
context:
space:
mode:
authorKate Tsuyu <kate@kxt.io>2020-08-28 08:58:51 -0400
committerKate Tsuyu <kate@kxt.io>2020-08-28 08:58:51 -0400
commit9dfb917c200eb97223bdfcda93c08e509fe1362f (patch)
treefdfa499d4489227bc1e57bfda4ddb35a0c7c8db7 /lib/std/math.zig
parent84d50c892d41850f666f05e05472c23ffabee434 (diff)
downloadzig-9dfb917c200eb97223bdfcda93c08e509fe1362f.tar.gz
zig-9dfb917c200eb97223bdfcda93c08e509fe1362f.zip
std: Add std.math.divCeil
Diffstat (limited to 'lib/std/math.zig')
-rw-r--r--lib/std/math.zig20
1 files changed, 20 insertions, 0 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig
index a76f0a391d..733d6b74b4 100644
--- a/lib/std/math.zig
+++ b/lib/std/math.zig
@@ -621,6 +621,26 @@ fn testDivFloor() void {
testing.expect((divFloor(f32, -5.0, 3.0) catch unreachable) == -2.0);
}
+pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T {
+ @setRuntimeSafety(false);
+ if (numerator <= 0) return divTrunc(T, numerator, denominator);
+ return (try divFloor(T, numerator - 1, denominator)) + 1;
+}
+
+test "math.divCeil" {
+ testDivCeil();
+ comptime testDivCeil();
+}
+fn testDivCeil() void {
+ testing.expect((divCeil(i32, 5, 3) catch unreachable) == 2);
+ testing.expect((divCeil(i32, -5, 3) catch unreachable) == -1);
+ testing.expectError(error.DivisionByZero, divCeil(i8, -5, 0));
+ testing.expectError(error.Overflow, divCeil(i8, -128, -1));
+
+ testing.expect((divCeil(f32, 5.0, 3.0) catch unreachable) == 2.0);
+ testing.expect((divCeil(f32, -5.0, 3.0) catch unreachable) == -1.0);
+}
+
pub fn divExact(comptime T: type, numerator: T, denominator: T) !T {
@setRuntimeSafety(false);
if (denominator == 0) return error.DivisionByZero;