Add approx equal functions

This commit is contained in:
Alex Selimov 2026-08-25 22:54:30 -04:00
parent 3a47ce9383
commit e51816fd45

View file

@ -43,10 +43,24 @@ pub fn vec3Cross(a: Vec3F64, b: Vec3F64) Vec3F64 {
return .init(x_component, y_component, z_component);
}
pub fn vec3ApproxEq(a: Vec3F64, b: Vec3F64, tol: f64) bool {
return @abs(a.x() - b.x()) < tol and
@abs(a.y() - b.y()) < tol and
@abs(a.z() - b.z()) < tol;
}
pub const Mat3F64 = struct {
row1: Vec3F64,
row2: Vec3F64,
row3: Vec3F64,
pub fn identity() Mat3F64 {
return .{
.row1 = .init(1, 0, 0),
.row2 = .init(0, 1, 0),
.row3 = .init(0, 0, 1),
};
}
};
pub fn mat3Add(a: Mat3F64, b: Mat3F64) Mat3F64 {
@ -134,6 +148,12 @@ pub fn vec3MulMat3(a: Mat3F64, b: Vec3F64) Vec3F64 {
);
}
pub fn mat3ApproxEq(a: Mat3F64, b: Mat3F64, tol: f64) bool {
return vec3ApproxEq(a.row1, b.row1, tol) and
vec3ApproxEq(a.row2, b.row2, tol) and
vec3ApproxEq(a.row3, b.row3, tol);
}
// Uses the Quaternion definition of q = w + xi + yj + zk
// and with i^2 = j^2 = k^2 = ijk = -1
// I grabbed a lot of this math from https://imadrahmoune.com/rotations-with-quaternions/
@ -243,6 +263,16 @@ test "vec3Cross crosses properly" {
try std.testing.expect(c.z() == -5);
}
test "vec3approxEq works" {
const a = Vec3F64.init(1, 0, 0);
var b = Vec3F64.init(1, 0, 0);
try std.testing.expect(vec3ApproxEq(a, b, 1e-12));
b.data[0] += 1e-11;
try std.testing.expect(!vec3ApproxEq(a, b, 1e-12));
try std.testing.expect(vec3ApproxEq(a, b, 1e-10));
}
test "Mat3 add works" {
const a: Mat3F64 = .{
.row1 = Vec3F64.init(1, 2, 3),
@ -346,6 +376,25 @@ test "mat inverse works" {
try std.testing.expectApproxEqAbs(-1.0 / 7.0, ainv.row3.y(), 1e-12);
try std.testing.expectApproxEqAbs(1.0 / 5.0, ainv.row3.z(), 1e-12);
}
test "mat3approxEq works" {
const a: Mat3F64 = .{
.row1 = Vec3F64.init(1, 2, 3),
.row2 = Vec3F64.init(4, 1, 5),
.row3 = Vec3F64.init(3, 1, 9),
};
var b: Mat3F64 = .{
.row1 = Vec3F64.init(1, 2, 3),
.row2 = Vec3F64.init(4, 1, 5),
.row3 = Vec3F64.init(3, 1, 9),
};
try std.testing.expect(mat3ApproxEq(a, b, 1e-12));
b.row2.data[1] += 1e-11;
try std.testing.expect(!mat3ApproxEq(a, b, 1e-12));
try std.testing.expect(mat3ApproxEq(a, b, 1e-12));
}
test "vec3 mul mat3 works" {
const b: Mat3F64 = .{
.row1 = Vec3F64.init(0, 1, 0),