float <--> int cast operations

This commit is contained in:
2026-08-31 23:50:08 -05:00
parent d981e50e7e
commit 3c3900a78d

View File

@@ -286,6 +286,56 @@ pub fn Matrix(rows: comptime_int, cols: comptime_int, T: type) type {
}.norm, }.norm,
else => @compileError("Connot take a square root on an integer matrix"), 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 }); const float = stackRows(f64, .{ 3, 4 });
try std.testing.expectEqual(5, float.norm()); 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));
}