pub struct Ratio { /* private fields */ }
Expand description
The ratio type.
It converts numerator / denominator
to mult / (1 << shift)
to avoid
u128
division on calculation. The shift
is as large as possible to
improve precision.
Currently, it only supports u32
as the numerator and denominator.
Implementations§
source§impl Ratio
impl Ratio
sourcepub const fn new(numerator: u32, denominator: u32) -> Self
pub const fn new(numerator: u32, denominator: u32) -> Self
Creates a new ratio numerator / denominator
.
sourcepub const fn inverse(&self) -> Self
pub const fn inverse(&self) -> Self
Get the inverse ratio.
Examples
use ratio::Ratio;
let ratio = Ratio::new(1, 2);
assert_eq!(ratio.inverse(), Ratio::new(2, 1));
sourcepub const fn mul_trunc(&self, value: u64) -> u64
pub const fn mul_trunc(&self, value: u64) -> u64
Multiplies the ratio by a value and rounds the result down.
Examples
use ratio::Ratio;
let ratio = Ratio::new(2, 3);
assert_eq!(ratio.mul_trunc(99), 66); // 99 * 2 / 3 = 66
assert_eq!(ratio.mul_trunc(100), 66); // trunc(100 * 2 / 3) = trunc(66.66...) = 66
sourcepub const fn mul_round(&self, value: u64) -> u64
pub const fn mul_round(&self, value: u64) -> u64
Multiplies the ratio by a value and rounds the result to the nearest whole number.
Examples
use ratio::Ratio;
let ratio = Ratio::new(2, 3);
assert_eq!(ratio.mul_round(99), 66); // 99 * 2 / 3 = 66
assert_eq!(ratio.mul_round(100), 67); // round(100 * 2 / 3) = round(66.66...) = 67
Trait Implementations§
Auto Trait Implementations§
impl RefUnwindSafe for Ratio
impl Send for Ratio
impl Sync for Ratio
impl Unpin for Ratio
impl UnwindSafe for Ratio
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more