float <--> int cast operations
This commit is contained in:
57
src/numz.zig
57
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));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user