Skip to content
This repository was archived by the owner on Apr 28, 2025. It is now read-only.

Commit 57b168c

Browse files
authored
Merge pull request #188 from m1el/negative-round
Fixed rounding to negative zero
2 parents 4dd3705 + 406bff1 commit 57b168c

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/math/round.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,20 @@ const TOINT: f64 = 1.0 / f64::EPSILON;
55
#[inline]
66
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
77
pub fn round(mut x: f64) -> f64 {
8-
let (f, i) = (x, x.to_bits());
8+
let i = x.to_bits();
99
let e: u64 = i >> 52 & 0x7ff;
1010
let mut y: f64;
1111

1212
if e >= 0x3ff + 52 {
1313
return x;
1414
}
15-
if i >> 63 != 0 {
16-
x = -x;
17-
}
1815
if e < 0x3ff - 1 {
1916
// raise inexact if x!=0
2017
force_eval!(x + TOINT);
21-
return 0.0 * f;
18+
return 0.0 * x;
19+
}
20+
if i >> 63 != 0 {
21+
x = -x;
2222
}
2323
y = x + TOINT - TOINT - x;
2424
if y > 0.5 {
@@ -35,3 +35,13 @@ pub fn round(mut x: f64) -> f64 {
3535
y
3636
}
3737
}
38+
39+
#[cfg(test)]
40+
mod tests {
41+
use super::round;
42+
43+
#[test]
44+
fn negative_zero() {
45+
assert_eq!(round(-0.0_f64).to_bits(), (-0.0_f64).to_bits());
46+
}
47+
}

src/math/roundf.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ pub fn roundf(mut x: f32) -> f32 {
1212
if e >= 0x7f + 23 {
1313
return x;
1414
}
15-
if i >> 31 != 0 {
16-
x = -x;
17-
}
1815
if e < 0x7f - 1 {
1916
force_eval!(x + TOINT);
2017
return 0.0 * x;
2118
}
19+
if i >> 31 != 0 {
20+
x = -x;
21+
}
2222
y = x + TOINT - TOINT - x;
2323
if y > 0.5f32 {
2424
y = y + x - 1.0;
@@ -33,3 +33,13 @@ pub fn roundf(mut x: f32) -> f32 {
3333
y
3434
}
3535
}
36+
37+
#[cfg(test)]
38+
mod tests {
39+
use super::roundf;
40+
41+
#[test]
42+
fn negative_zero() {
43+
assert_eq!(roundf(-0.0_f32).to_bits(), (-0.0_f32).to_bits());
44+
}
45+
}

0 commit comments

Comments
 (0)