Skip to main content

Module entrywise_shr_round

Module entrywise_shr_round 

Source
Expand description

Right-shifting a vector (dividing it by a power of 2) and rounding every element, by implementations of EntrywiseShrRound and EntrywiseShrRoundAssign.

§entrywise_shr_round

use core::str::FromStr;
use malachite_base::num::arithmetic::traits::EntrywiseShrRound;
use malachite_base::rounding_modes::RoundingMode::*;
use malachite_base::unsigned_vector::UnsignedVector;

let v = UnsignedVector::<u8>::from_str("(1, 2, 3, 5)").unwrap();
assert_eq!(
    (&v).entrywise_shr_round(1u8, Floor).to_string(),
    "(0, 1, 1, 2)"
);
assert_eq!(
    (&v).entrywise_shr_round(1u16, Ceiling).to_string(),
    "(1, 1, 2, 3)"
);
// Ties round to even.
assert_eq!(
    (&v).entrywise_shr_round(1u32, Nearest).to_string(),
    "(0, 1, 2, 2)"
);
assert_eq!(
    UnsignedVector::<u8>::from_str("(4, 8, 12)")
        .unwrap()
        .entrywise_shr_round(2u64, Exact)
        .to_string(),
    "(1, 2, 3)"
);
// Shifting by at least the width rounds every element to 0 or 1.
assert_eq!(
    UnsignedVector::<u8>::from_str("(255, 128, 127)")
        .unwrap()
        .entrywise_shr_round(8u8, Nearest)
        .to_string(),
    "(1, 0, 0)"
);
assert_eq!(
    UnsignedVector::<u8>::from_str("(255, 1, 0)")
        .unwrap()
        .entrywise_shr_round(100u128, Ceiling)
        .to_string(),
    "(1, 1, 0)"
);

§entrywise_shr_round_assign

use core::str::FromStr;
use malachite_base::num::arithmetic::traits::EntrywiseShrRoundAssign;
use malachite_base::rounding_modes::RoundingMode::*;
use malachite_base::unsigned_vector::UnsignedVector;

let mut v = UnsignedVector::<u8>::from_str("(1, 2, 3, 5)").unwrap();
v.entrywise_shr_round_assign(1u8, Nearest);
assert_eq!(v.to_string(), "(0, 1, 2, 2)");

let mut v = UnsignedVector::<u8>::from_str("(1, 2, 3, 5)").unwrap();
v.entrywise_shr_round_assign(1u32, Up);
assert_eq!(v.to_string(), "(1, 1, 2, 3)");