Skip to content

Commit

Permalink
Merge pull request #253 from bvinc/round_slow
Browse files Browse the repository at this point in the history
Optimize round and roundf
  • Loading branch information
Lokathor authored Jul 2, 2021
2 parents c2d22bf + 842592e commit aa030b8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 62 deletions.
46 changes: 14 additions & 32 deletions src/math/round.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,10 @@
use super::copysign;
use super::trunc;
use core::f64;

const TOINT: f64 = 1.0 / f64::EPSILON;

#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn round(mut x: f64) -> f64 {
let i = x.to_bits();
let e: u64 = i >> 52 & 0x7ff;
let mut y: f64;

if e >= 0x3ff + 52 {
return x;
}
if e < 0x3ff - 1 {
// raise inexact if x!=0
force_eval!(x + TOINT);
return 0.0 * x;
}
if i >> 63 != 0 {
x = -x;
}
y = x + TOINT - TOINT - x;
if y > 0.5 {
y = y + x - 1.0;
} else if y <= -0.5 {
y = y + x + 1.0;
} else {
y = y + x;
}

if i >> 63 != 0 {
-y
} else {
y
}
pub fn round(x: f64) -> f64 {
trunc(x + copysign(0.5 - 0.25 * f64::EPSILON, x))
}

#[cfg(test)]
Expand All @@ -43,4 +15,14 @@ mod tests {
fn negative_zero() {
assert_eq!(round(-0.0_f64).to_bits(), (-0.0_f64).to_bits());
}

#[test]
fn sanity_check() {
assert_eq!(round(-1.0), -1.0);
assert_eq!(round(2.8), 3.0);
assert_eq!(round(-0.5), -1.0);
assert_eq!(round(0.5), 1.0);
assert_eq!(round(-1.5), -2.0);
assert_eq!(round(1.5), 2.0);
}
}
44 changes: 14 additions & 30 deletions src/math/roundf.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,10 @@
use super::copysignf;
use super::truncf;
use core::f32;

const TOINT: f32 = 1.0 / f32::EPSILON;

#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn roundf(mut x: f32) -> f32 {
let i = x.to_bits();
let e: u32 = i >> 23 & 0xff;
let mut y: f32;

if e >= 0x7f + 23 {
return 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;
} else if y <= -0.5f32 {
y = y + x + 1.0;
} else {
y = y + x;
}
if i >> 31 != 0 {
-y
} else {
y
}
pub fn roundf(x: f32) -> f32 {
truncf(x + copysignf(0.5 - 0.25 * f32::EPSILON, x))
}

#[cfg(test)]
Expand All @@ -41,4 +15,14 @@ mod tests {
fn negative_zero() {
assert_eq!(roundf(-0.0_f32).to_bits(), (-0.0_f32).to_bits());
}

#[test]
fn sanity_check() {
assert_eq!(roundf(-1.0), -1.0);
assert_eq!(roundf(2.8), 3.0);
assert_eq!(roundf(-0.5), -1.0);
assert_eq!(roundf(0.5), 1.0);
assert_eq!(roundf(-1.5), -2.0);
assert_eq!(roundf(1.5), 2.0);
}
}

0 comments on commit aa030b8

Please sign in to comment.