Skip to content

Commit e34c31b

Browse files
committed
Use constant for 180/π in to_degrees
The current `f32|f64.to_degrees` implementation uses a division to calculate 180/π, which causes a loss of precision. Using a constant is still not perfect (implementing a maximally-precise algorithm would come with a high performance cost), but improves precision with a minimal change.
1 parent 90eb44a commit e34c31b

File tree

3 files changed

+7
-1
lines changed

3 files changed

+7
-1
lines changed

src/libcore/num/f32.rs

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

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

src/libcore/num/f64.rs

+3
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,9 @@ impl Float for f64 {
237237
/// Converts to degrees, assuming the number is in radians.
238238
#[inline]
239239
fn to_degrees(self) -> f64 {
240+
// The division here is correctly rounded with respect to the true
241+
// value of 180/π. (This differs from f32, where a constant must be
242+
// used to ensure a correctly rounded result.)
240243
self * (180.0f64 / consts::PI)
241244
}
242245

src/libstd/f32.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1531,6 +1531,7 @@ mod tests {
15311531
assert!(nan.to_degrees().is_nan());
15321532
assert_eq!(inf.to_degrees(), inf);
15331533
assert_eq!(neg_inf.to_degrees(), neg_inf);
1534+
assert_eq!(1_f32.to_degrees(), 57.2957795130823208767981548141051703);
15341535
}
15351536

15361537
#[test]

0 commit comments

Comments
 (0)