#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Binary32 {
mantissa: i64,
exponent: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Rounding {
Nearest,
Down,
}
impl Binary32 {
pub const BITS: u32 = 24;
pub const ZERO: Self = Self {
mantissa: 0,
exponent: 0,
};
#[must_use]
pub const fn mantissa(self) -> i64 {
self.mantissa
}
#[must_use]
pub const fn exponent(self) -> i32 {
self.exponent
}
#[must_use]
pub fn nearest(numerator: i128, denominator: i128) -> Self {
Self::quotient(numerator, denominator, Rounding::Nearest)
}
#[must_use]
pub fn below(numerator: i128, denominator: i128) -> Self {
Self::quotient(numerator, denominator, Rounding::Down)
}
fn quotient(numerator: i128, denominator: i128, rounding: Rounding) -> Self {
if numerator == 0 || denominator <= 0 {
return Self::ZERO;
}
let (quotient, rest, scale) =
scaled_quotient(numerator.unsigned_abs(), denominator.unsigned_abs());
Self::rounded(
(quotient << 1) | u128::from(rest),
-scale - 1,
numerator < 0,
rounding,
)
}
fn rounded(magnitude: u128, exponent: i32, negative: bool, rounding: Rounding) -> Self {
if magnitude == 0 {
return Self::ZERO;
}
let short = magnitude
.leading_zeros()
.saturating_sub(u128::BITS - Self::BITS);
let mut magnitude = magnitude << short;
let mut exponent = exponent - short.cast_signed();
let mut lost = false;
while magnitude >= (1 << (Self::BITS + 1)) {
lost |= magnitude & 1 == 1;
magnitude >>= 1;
exponent += 1;
}
if magnitude >= (1 << Self::BITS) {
let half = magnitude & 1 == 1;
magnitude >>= 1;
exponent += 1;
let up = match rounding {
Rounding::Nearest => half && (lost || magnitude & 1 == 1),
Rounding::Down => negative && (half || lost),
};
if up {
magnitude += 1;
}
if magnitude == 1 << Self::BITS {
magnitude >>= 1;
exponent += 1;
}
}
let mantissa = i64::try_from(magnitude).unwrap_or(i64::MAX);
Self {
mantissa: if negative { -mantissa } else { mantissa },
exponent,
}
}
fn aligned(self, other: Self) -> (i128, i128, i32) {
if self.mantissa == 0 {
return (0, other.mantissa.into(), other.exponent);
}
if other.mantissa == 0 {
return (self.mantissa.into(), 0, self.exponent);
}
let by = self.exponent.abs_diff(other.exponent);
if by <= i64::BITS {
let exponent = self.exponent.min(other.exponent);
let shift =
|number: Self| i128::from(number.mantissa) << number.exponent.abs_diff(exponent);
return (shift(self), shift(other), exponent);
}
let up = i64::BITS - Self::BITS;
let exponent = self.exponent.max(other.exponent) - up.cast_signed();
let multiple = |number: Self| {
if number.exponent > exponent {
i128::from(number.mantissa) << up
} else {
i128::from(number.mantissa.signum())
}
};
(multiple(self), multiple(other), exponent)
}
fn sum(self, other: Self, rounding: Rounding) -> Self {
let (first, second, exponent) = self.aligned(other);
let sum = first + second;
Self::rounded(sum.unsigned_abs(), exponent, sum < 0, rounding)
}
#[must_use]
pub fn plus(self, other: Self) -> Self {
self.sum(other, Rounding::Nearest)
}
#[must_use]
pub fn plus_below(self, other: Self) -> Self {
self.sum(other, Rounding::Down)
}
#[must_use]
pub fn minus(self, other: Self) -> Self {
self.plus(Self {
mantissa: -other.mantissa,
..other
})
}
#[must_use]
pub fn times(self, factor: i64) -> Self {
self.scaled(i128::from(factor), 0, Rounding::Nearest)
}
#[must_use]
pub fn times_below(self, factor: i64) -> Self {
self.scaled(i128::from(factor), 0, Rounding::Down)
}
#[must_use]
pub fn product_below(self, other: Self) -> Self {
self.scaled(i128::from(other.mantissa), other.exponent, Rounding::Down)
}
fn scaled(self, factor: i128, exponent: i32, rounding: Rounding) -> Self {
let product = i128::from(self.mantissa) * factor;
Self::rounded(
product.unsigned_abs(),
self.exponent + exponent,
product < 0,
rounding,
)
}
#[must_use]
pub fn over(self, other: Self) -> Self {
self.divided(other, Rounding::Nearest)
}
#[must_use]
pub fn over_below(self, other: Self) -> Self {
self.divided(other, Rounding::Down)
}
fn divided(self, other: Self, rounding: Rounding) -> Self {
if other.mantissa == 0 {
return Self::ZERO;
}
let sign = other.mantissa.signum();
let quotient = Self::quotient(
i128::from(self.mantissa * sign),
i128::from(other.mantissa * sign),
rounding,
);
if quotient.mantissa == 0 {
return Self::ZERO;
}
Self {
exponent: quotient.exponent + self.exponent - other.exponent,
..quotient
}
}
#[must_use]
pub fn floor(self) -> i64 {
if self.exponent >= 0 {
return self.whole(false);
}
let by = self.exponent.unsigned_abs();
if by >= i64::BITS - 1 {
return if self.mantissa < 0 { -1 } else { 0 };
}
self.mantissa.div_euclid(1_i64 << by)
}
#[must_use]
pub fn reaches(self, other: Self) -> bool {
let (first, second, _) = self.aligned(other);
first.unsigned_abs() >= second.unsigned_abs()
}
#[must_use]
pub fn toward_zero(self) -> i64 {
if self.exponent >= 0 {
return self.whole(false);
}
let by = self.exponent.unsigned_abs();
if by >= i64::BITS - 1 {
return 0;
}
self.mantissa / (1_i64 << by)
}
#[must_use]
pub fn whole(self, lower: bool) -> i64 {
if self.exponent >= 0 {
let up = self.exponent.unsigned_abs();
if up >= i64::BITS - Self::BITS {
return if self.mantissa < 0 {
i64::MIN
} else {
i64::MAX
};
}
return self.mantissa << up;
}
let by = self.exponent.unsigned_abs();
if by >= i64::BITS - 1 {
return 0;
}
let divisor = 1_i64 << by;
let whole = self.mantissa.div_euclid(divisor);
let rest = self.mantissa.rem_euclid(divisor);
whole
+ i64::from(if lower {
2 * rest > divisor
} else {
2 * rest >= divisor
})
}
#[must_use]
pub fn differs_by(self, other: Self, numerator: i64, denominator: i64) -> bool {
let parts = (
u32::try_from(numerator.unsigned_abs()),
u32::try_from(denominator),
);
debug_assert!(
matches!(parts, (Ok(_), Ok(1..))),
"differs_by takes parts below 2^32 and a positive denominator, not \
{numerator}/{denominator}"
);
let (Ok(numerator), Ok(denominator @ 1..)) = parts else {
return false;
};
let (first, second, exponent) = self.aligned(other);
let difference = (first - second).unsigned_abs() * u128::from(denominator);
let limit = u128::from(numerator);
let by = exponent.unsigned_abs();
if exponent >= 0 {
let whole = limit.checked_shr(by).unwrap_or(0);
let rest = whole.checked_shl(by) != Some(limit);
difference >= whole + u128::from(rest)
} else {
difference.checked_shr(by).unwrap_or(0) >= limit
}
}
}
fn scaled_quotient(top: u128, bottom: u128) -> (u128, bool, i32) {
let scale = (Binary32::BITS + 1 + top.leading_zeros()).cast_signed()
- bottom.leading_zeros().cast_signed();
if scale < 0 {
let down = scale.unsigned_abs();
let (quotient, rest) = divided(top >> down, bottom);
return (quotient, rest || top.trailing_zeros() < down, scale);
}
let up = scale.unsigned_abs();
if up <= top.leading_zeros() {
let (quotient, rest) = divided(top << up, bottom);
return (quotient, rest, scale);
}
let (mut quotient, mut rest) = (top / bottom, top % bottom);
for _ in 0..up {
rest <<= 1;
quotient <<= 1;
if rest >= bottom {
rest -= bottom;
quotient |= 1;
}
}
(quotient, rest != 0, scale)
}
fn divided(top: u128, bottom: u128) -> (u128, bool) {
if let (Ok(top), Ok(bottom)) = (u64::try_from(top), u64::try_from(bottom)) {
return (u128::from(top / bottom), top % bottom != 0);
}
let quotient = top / bottom;
(quotient, top - quotient * bottom != 0)
}
#[cfg(test)]
mod tests;