Skip to content

Commit 2d11f04

Browse files
committed
Fix an accuracy regression in f32::to_degrees
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.
1 parent 0ff9872 commit 2d11f04

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

src/libcore/num/f32.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -239,9 +239,7 @@ impl Float for f32 {
239239
/// Converts to degrees, assuming the number is in radians.
240240
#[inline]
241241
fn to_degrees(self) -> f32 {
242-
// Use a constant for better precision.
243-
const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
244-
self * PIS_IN_180
242+
(self as f64).to_degrees() as f32
245243
}
246244

247245
/// Converts to radians, assuming the number is in degrees.

src/libstd/f32.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1532,6 +1532,10 @@ mod tests {
15321532
assert_eq!(inf.to_degrees(), inf);
15331533
assert_eq!(neg_inf.to_degrees(), neg_inf);
15341534
assert_eq!(1_f32.to_degrees(), 57.2957795130823208767981548141051703);
1535+
assert_eq!(f32::consts::FRAC_PI_6.to_degrees(), 30.0f32);
1536+
assert_eq!(f32::consts::FRAC_PI_3.to_degrees(), 60.0f32);
1537+
assert_eq!(30.0f32.to_degrees().to_radians(), 30.0f32);
1538+
assert_eq!(30.0f32.to_radians().to_degrees(), 30.0f32);
15351539
}
15361540

15371541
#[test]

0 commit comments

Comments
 (0)