Skip to content

Commit

Permalink
Use checked_sub for inverse approximation
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsided committed Jul 9, 2024
1 parent 04e885c commit 062733b
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/float/inv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ use super::F32;
impl F32 {
/// Fast approximation of `1/x`.
pub fn inv(self) -> Self {
// Check if the value is too large for the approximation, NaN (e.g. 0x7fC0_0000) or infinity.
let bits = self.0.to_bits();
if bits >= 0x7f00_0000 {
return if self.0.is_infinite() {
// Perform the bit manipulation for the approximation
// The constant 0x7f00_0000 corresponds to the bit pattern for 1.0 in IEEE 754 format.
// Subtracting the bits of the original number from this constant effectively inverts the exponent,
// resulting in an approximation of the reciprocal.
match 0x7f00_0000_u32.checked_sub(self.0.to_bits()) {
Some(result) => Self(f32::from_bits(result)),
// Check if the value is too large for the approximation, NaN (e.g. 0x7fC0_0000) or infinity.
None => if self.0.is_infinite() {
// 1/∞ = 0; by definition.
if self.0.is_sign_positive() {
Self(0.0)
Expand All @@ -24,12 +28,6 @@ impl F32 {
Self(0.0)
}
}

// Perform the bit manipulation for the approximation
// The constant 0x7f00_0000 corresponds to the bit pattern for 1.0 in IEEE 754 format.
// Subtracting the bits of the original number from this constant effectively inverts the exponent,
// resulting in an approximation of the reciprocal.
Self(f32::from_bits(0x7f00_0000 - bits))
}
}

Expand Down

0 comments on commit 062733b

Please sign in to comment.