Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for rem_euclid for Signed types #494

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,25 @@ macro_rules! system {
value: self.value.min(other.value),
}
}

/// Calculates the Euclidean remainder (least nonnegative remainder) of a quantity
/// modulo `modulus`. The return value should be in the interval [0, |modulus|)`, but
/// rarely, due to rounding error resulting from finite floating point precision, the
/// return value can be `|modulus|`.
#[must_use = "method returns a new number and does not mutate the original value"]
#[inline(always)]
pub fn rem_euclid(self, modulus: Self) -> Self
where
V: $crate::num::Signed,
{
// The Signed trait does not provide rem_euclid, so it must be implemented
let rem = self.value % modulus.value.abs();
Quantity {
dimension: $crate::lib::marker::PhantomData,
units: $crate::lib::marker::PhantomData,
value: if rem.is_negative() { rem + modulus.value.abs() } else { rem },
}
}
}

// Explicitly definte floating point methods for float and complex storage types.
Expand Down
20 changes: 20 additions & 0 deletions src/tests/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,26 @@ mod signed {
Test::eq(&Length::new::<meter>(-(*l).clone()),
&-Length::new::<meter>((*l).clone()))
}

#[allow(trivial_casts)]
fn rem_euclid(v: A<V>) -> bool {
let two = V::one() + V::one();

// NB: The builtin v.rem_euclid() will sometimes return a finite result when v is
// infinite. The result should be undefined (NaN).
let exp_res = if v.is_infinite() { V::nan() } else { v.rem_euclid(two) };

let act_res = Length::new::<meter>(*v).rem_euclid(Length::new::<meter>(two)).value;

// Finite precision floating point can result in exp_res being -0.0. This messes up
// test comparison, since the implementation being tested will map a -0.0 to the
// modulus.
if exp_res.is_sign_negative() {
Test::eq(&two, &act_res)
} else {
Test::eq(&exp_res, &act_res)
}
}
}
}
}
Expand Down