Skip to content

Commit

Permalink
Fix an accuracy regression in f32::to_degrees
Browse files Browse the repository at this point in the history
rust-lang#47919 regressed some test cases for `f32::to_degrees`, while improving others. This change satisfies all previous test cases and should be more accurate than both previous implementations.

The `f32` to `f64` cast is lossless, `f64::to_degrees` should provide more accuracy than a native `f32::to_degrees`, and conversion back to `f32` will be as accurate a conversion as possible. It can be hard to reason about floating-point accuracy, but given that this passes all the tests, I feel confident it's an improvement.
  • Loading branch information
varkor committed Feb 28, 2018
1 parent 0ff9872 commit 2d11f04
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/libcore/num/f32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,7 @@ impl Float for f32 {
/// Converts to degrees, assuming the number is in radians.
#[inline]
fn to_degrees(self) -> f32 {
// Use a constant for better precision.
const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
self * PIS_IN_180
(self as f64).to_degrees() as f32
}

/// Converts to radians, assuming the number is in degrees.
Expand Down
4 changes: 4 additions & 0 deletions src/libstd/f32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1532,6 +1532,10 @@ mod tests {
assert_eq!(inf.to_degrees(), inf);
assert_eq!(neg_inf.to_degrees(), neg_inf);
assert_eq!(1_f32.to_degrees(), 57.2957795130823208767981548141051703);
assert_eq!(f32::consts::FRAC_PI_6.to_degrees(), 30.0f32);
assert_eq!(f32::consts::FRAC_PI_3.to_degrees(), 60.0f32);
assert_eq!(30.0f32.to_degrees().to_radians(), 30.0f32);
assert_eq!(30.0f32.to_radians().to_degrees(), 30.0f32);
}

#[test]
Expand Down

0 comments on commit 2d11f04

Please sign in to comment.