use core::fmt::Debug;
pub trait Coefficient: Copy + PartialOrd + Debug + Send + Sync + 'static {
const ZERO: Self;
const ONE: Self;
const ISING_SCALE: Self;
#[must_use]
fn plus(self, rhs: Self) -> Self;
#[must_use]
fn minus(self, rhs: Self) -> Self;
#[must_use]
fn times(self, rhs: Self) -> Self;
#[must_use]
fn from_quadruple(quadruple: Self) -> Self;
#[must_use]
fn exact_div(self, divisor: Self) -> Option<Self>;
#[must_use]
fn from_u32(value: u32) -> Self;
#[must_use]
fn to_f64(self) -> f64;
}
impl Coefficient for i64 {
const ZERO: Self = 0;
const ONE: Self = 1;
const ISING_SCALE: Self = 4;
fn plus(self, rhs: Self) -> Self {
self.checked_add(rhs)
.expect("i64 coefficient overflow in addition")
}
fn minus(self, rhs: Self) -> Self {
self.checked_sub(rhs)
.expect("i64 coefficient overflow in subtraction")
}
fn times(self, rhs: Self) -> Self {
self.checked_mul(rhs)
.expect("i64 coefficient overflow in multiplication")
}
fn from_quadruple(quadruple: Self) -> Self {
quadruple
}
fn exact_div(self, divisor: Self) -> Option<Self> {
(self.checked_rem(divisor)? == 0).then(|| self / divisor)
}
fn from_u32(value: u32) -> Self {
Self::from(value)
}
#[expect(
clippy::cast_precision_loss,
reason = "only acceptance probabilities use the value; the trait docs state the 2^53 limit"
)]
fn to_f64(self) -> f64 {
self as f64
}
}
impl Coefficient for f64 {
const ZERO: Self = 0.0;
const ONE: Self = 1.0;
const ISING_SCALE: Self = 1.0;
fn plus(self, rhs: Self) -> Self {
self + rhs
}
fn minus(self, rhs: Self) -> Self {
self - rhs
}
fn times(self, rhs: Self) -> Self {
self * rhs
}
fn from_quadruple(quadruple: Self) -> Self {
quadruple * 0.25
}
fn exact_div(self, divisor: Self) -> Option<Self> {
Some(self / divisor)
}
fn from_u32(value: u32) -> Self {
Self::from(value)
}
fn to_f64(self) -> f64 {
self
}
}
#[cfg(test)]
mod tests {
use super::Coefficient;
#[test]
fn i64_exact_div_rejects_remainders() {
assert_eq!(12_i64.exact_div(4), Some(3));
assert_eq!(13_i64.exact_div(4), None);
assert_eq!(13_i64.exact_div(0), None);
}
#[test]
#[should_panic(expected = "overflow")]
fn i64_overflow_panics() {
let _ = i64::MAX.plus(1);
}
#[test]
fn quadruple_applies_the_scale() {
assert_eq!(i64::from_quadruple(6), 6);
assert!((f64::from_quadruple(6.0) - 1.5).abs() < f64::EPSILON);
}
}