Skip to content

Commit

Permalink
feat: faster rounding with bitwise and operation
Browse files Browse the repository at this point in the history
  • Loading branch information
lavafroth committed Jan 22, 2024
1 parent 7523fd2 commit 8a92e5e
Showing 1 changed file with 4 additions and 12 deletions.
16 changes: 4 additions & 12 deletions src/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,22 +206,14 @@ pub fn format_duration(duration: std::time::Duration) -> String {
/// round-half-up behaviour. I had tried using math::round::half_to_even, but that didn't seem to
/// work correctly (rounded 42.55 to 42).
pub fn bankers_rounding(float: f64) -> u32 {
let fractional_part = float - float.floor();
let rounded_down = float as u32;
if fractional_part < 0.5 {
return rounded_down;
} else if fractional_part > 0.5 {
return rounded_down + 1;
} else { // fractional_part == 0.5
if rounded_down % 2 == 0 { // is even
return rounded_down;
} else {
return rounded_down + 1;
}
match float.fract() {
f if f < 0.5 => rounded_down,
f if f > 0.5 => rounded_down + 1,
_ => rounded_down + (rounded_down & 1),
}
}


#[cfg(test)]
mod tests {
use flate2::Compression;
Expand Down

0 comments on commit 8a92e5e

Please sign in to comment.