Optimized length to be optimized for int

This commit is contained in:
AdrienBouvais 2026-04-21 11:43:29 +02:00
parent 38bf79e741
commit a484e2e7da

View File

@ -288,23 +288,18 @@ pub fn QuantityVec3(Q: type) type {
} }
pub fn length(self: Self) T { pub fn length(self: Self) T {
if (comptime hlp.isInt(T)) const len_sq = self.lengthSqr();
return self.isqrt()
else
return @sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
}
fn isqrt(self: Self) T { if (comptime @typeInfo(T) == .int) {
const squared_sum = (self.x * self.x) + (self.y * self.y) + (self.z * self.z); // Construct the unsigned equivalent of T at comptime (e.g., i32 -> u32)
if (squared_sum <= 0) return 0; const UnsignedT = @Int(.unsigned, @typeInfo(T).int.bits);
var x = squared_sum; // len_sq is always positive, so @intCast is perfectly safe
var y = @divTrunc(x + 1, 2); const u_len_sq = @as(UnsignedT, @intCast(len_sq));
while (y < x) { return @as(T, @intCast(std.math.sqrt(u_len_sq)));
x = y; } else {
y = @divTrunc(x + @divTrunc(squared_sum, x), 2); return @sqrt(len_sq);
} }
return x;
} }
}; };
} }