smarter sqrt

This commit is contained in:
Quaternions 2024-08-29 12:12:14 -07:00
parent 3d3eb966a4
commit 8ba76c7a00

View File

@ -289,25 +289,17 @@ impl<const CHUNKS:usize,Frac:Unsigned> Fixed<CHUNKS,Frac>
Fixed::<CHUNKS,Frac>:std::ops::Mul<Fixed<CHUNKS,Frac>,Output=Fixed<CHUNKS,Frac>>,
{
pub fn sqrt_unchecked(self)->Self{
//find pow2 more powerful than self
let mut pow2=if Self::ONE<self{
let mut pow2=Self::TWO;//1<self is so bake one iteration
while pow2<=self{
pow2<<=1;
}
pow2
}else if Self::ONE==self{
return Self::ONE;
}else if Self::ZERO<self{
let mut pow2=Self::ONE;
while self<=pow2{
pow2>>=1;
}
pow2
}else{//either 0==self or self is negative
return Self::ZERO;
//pow2 must be the minimum power of two which when squared is greater than self
//0001.0000 Fixed<u8,4>
//sqrt
//0110.0000
//pow2 = 0100.0000
let mut pow2=Self{
bits:BInt::<CHUNKS>::ONE.shl((((CHUNKS as i32*64-Frac::I32-(self.bits.leading_zeros() as i32)+1)>>1)+Frac::I32) as u32),
frac:PhantomData,
};
let mut result=pow2;
let mut result=pow2>>1;
while pow2!=Self::ZERO{
pow2>>=1;
let new_result=result+pow2;