From 9a25274bb03340704ac4c36145ac7c3df812716f Mon Sep 17 00:00:00 2001 From: Corwin Kuiper Date: Mon, 6 Dec 2021 19:49:27 +0000 Subject: [PATCH] switched the magnitude function to use the alpha max + beta min algorithm --- agb/src/number.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/agb/src/number.rs b/agb/src/number.rs index 3db154f9..0914a2fa 100644 --- a/agb/src/number.rs +++ b/agb/src/number.rs @@ -378,13 +378,6 @@ impl Num { } } -impl Num { - pub fn sqrt(self) -> Self { - assert_eq!(N % 2, 0, "N must be even to be able to square root"); - Self(syscall::sqrt(self.0) << (N / 2)) - } -} - #[test_case] fn test_numbers(_gba: &mut super::Gba) { // test addition @@ -696,9 +689,17 @@ impl Vector2D> { self.x.abs() + self.y.abs() } + // calculates the magnitude of a vector using the alpha max plus beta min + // algorithm https://en.wikipedia.org/wiki/Alpha_max_plus_beta_min_algorithm + // this has a maximum error of less than 4% of the true magnitude, probably + // depending on the size of your fixed point approximation pub fn magnitude(self) -> Num { - self.magnitude_squared().sqrt() + let max = core::cmp::max(self.x, self.y); + let min = core::cmp::min(self.x, self.y); + + max * num!(0.960433870103) + min * num!(0.397824734759) } + pub fn normalise(self) -> Self { self / self.magnitude() }