Merge pull request #188 from m1el/negative-round

Fixed rounding to negative zero
This commit is contained in:
gnzlbg
2019-07-01 16:38:33 +02:00
committed by GitHub
2 changed files with 28 additions and 8 deletions
+15 -5
View File
@@ -5,20 +5,20 @@ const TOINT: f64 = 1.0 / f64::EPSILON;
#[inline]
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn round(mut x: f64) -> f64 {
let (f, i) = (x, x.to_bits());
let i = x.to_bits();
let e: u64 = i >> 52 & 0x7ff;
let mut y: f64;
if e >= 0x3ff + 52 {
return x;
}
if i >> 63 != 0 {
x = -x;
}
if e < 0x3ff - 1 {
// raise inexact if x!=0
force_eval!(x + TOINT);
return 0.0 * f;
return 0.0 * x;
}
if i >> 63 != 0 {
x = -x;
}
y = x + TOINT - TOINT - x;
if y > 0.5 {
@@ -35,3 +35,13 @@ pub fn round(mut x: f64) -> f64 {
y
}
}
#[cfg(test)]
mod tests {
use super::round;
#[test]
fn negative_zero() {
assert_eq!(round(-0.0_f64).to_bits(), (-0.0_f64).to_bits());
}
}
+13 -3
View File
@@ -12,13 +12,13 @@ pub fn roundf(mut x: f32) -> f32 {
if e >= 0x7f + 23 {
return x;
}
if i >> 31 != 0 {
x = -x;
}
if e < 0x7f - 1 {
force_eval!(x + TOINT);
return 0.0 * x;
}
if i >> 31 != 0 {
x = -x;
}
y = x + TOINT - TOINT - x;
if y > 0.5f32 {
y = y + x - 1.0;
@@ -33,3 +33,13 @@ pub fn roundf(mut x: f32) -> f32 {
y
}
}
#[cfg(test)]
mod tests {
use super::roundf;
#[test]
fn negative_zero() {
assert_eq!(roundf(-0.0_f32).to_bits(), (-0.0_f32).to_bits());
}
}