From 3c3900a78d05b66e7149d41a38d5e6add29645ec Mon Sep 17 00:00:00 2001 From: Robert H Date: Mon, 31 Aug 2026 23:50:08 -0500 Subject: [PATCH] float <--> int cast operations --- src/numz.zig | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/numz.zig b/src/numz.zig index bf40bd9..7a0c06c 100644 --- a/src/numz.zig +++ b/src/numz.zig @@ -286,6 +286,56 @@ pub fn Matrix(rows: comptime_int, cols: comptime_int, T: type) type { }.norm, else => @compileError("Connot take a square root on an integer matrix"), }; + + pub fn floatFromInt(self: Self, F: type) Matrix(rows, cols, F) { + var result: Matrix(rows, cols, F) = .{ .mat = undefined }; + inline for (&result.mat, self.mat) |*r_row, s_row| { + inline for (r_row, s_row) |*r, s| { + r.* = @floatFromInt(s); + } + } + return result; + } + + pub fn round(self: Self, I: type) Matrix(rows, cols, I) { + var result: Matrix(rows, cols, I) = .{ .mat = undefined }; + inline for (&result.mat, self.mat) |*r_row, s_row| { + inline for (r_row, s_row) |*r, s| { + r.* = @round(s); + } + } + return result; + } + + pub fn floor(self: Self, I: type) Matrix(rows, cols, I) { + var result: Matrix(rows, cols, I) = .{ .mat = undefined }; + inline for (&result.mat, self.mat) |*r_row, s_row| { + inline for (r_row, s_row) |*r, s| { + r.* = @floor(s); + } + } + return result; + } + + pub fn ceil(self: Self, I: type) Matrix(rows, cols, I) { + var result: Matrix(rows, cols, I) = .{ .mat = undefined }; + inline for (&result.mat, self.mat) |*r_row, s_row| { + inline for (r_row, s_row) |*r, s| { + r.* = @ceil(s); + } + } + return result; + } + + pub fn trunc(self: Self, I: type) Matrix(rows, cols, I) { + var result: Matrix(rows, cols, I) = .{ .mat = undefined }; + inline for (&result.mat, self.mat) |*r_row, s_row| { + inline for (r_row, s_row) |*r, s| { + r.* = @trunc(s); + } + } + return result; + } }; } @@ -498,3 +548,10 @@ test "norm" { const float = stackRows(f64, .{ 3, 4 }); try std.testing.expectEqual(5, float.norm()); } + +test "cast" { + try std.testing.expectEqual(@as(f64, 3), stackRows(u32, .{ 3 }).floatFromInt(f64).get(.x)); + try std.testing.expectEqual(@as(i32, -4), stackRows(f64, .{ -3.5 }).round(i32).get(.x)); + try std.testing.expectEqual(@as(i32, 4), stackRows(f64, .{ 3.5 }).ceil(i32).get(.x)); + try std.testing.expectEqual(@as(i32, 3), stackRows(f64, .{ 3.5 }).floor(i32).get(.x)); +}