Skip to content

Use constant for 180/π in f32::to_degrees #61

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

Merged
merged 3 commits into from
May 4, 2018
Merged
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
17 changes: 16 additions & 1 deletion src/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,9 @@ impl FloatCore for f32 {
#[inline]
#[cfg(not(feature = "std"))]
fn to_degrees(self) -> Self {
self * (180.0 / f32::consts::PI)
// Use a constant for better precision.
const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
self * PIS_IN_180
}

#[inline]
Expand Down Expand Up @@ -841,6 +843,9 @@ impl FloatCore for f64 {
#[inline]
#[cfg(not(feature = "std"))]
fn to_degrees(self) -> Self {
// The division here is correctly rounded with respect to the true
// value of 180/π. (This differs from f32, where a constant must be
// used to ensure a correctly rounded result.)
self * (180.0 / f64::consts::PI)
}

Expand Down Expand Up @@ -2008,4 +2013,14 @@ mod tests {
assert!((Float::to_radians(deg) - rad).abs() < 1e-5);
}
}

#[test]
// This fails with the forwarded `std` implementation in Rust 1.8.
// To avoid the failure, the test is limited to `no_std` builds.
#[cfg(not(feature = "std"))]
fn to_degrees_rounding() {
use float::FloatCore;

assert_eq!(FloatCore::to_degrees(1_f32), 57.2957795130823208767981548141051703);
}
}