Function malachite_base::num::conversion::mantissa_and_exponent::sci_mantissa_and_exponent_with_rounding
source · [−]pub fn sci_mantissa_and_exponent_with_rounding<T: PrimitiveUnsigned, U: PrimitiveFloat>(
x: T,
rm: RoundingMode
) -> Option<(U, u64)>
Expand description
Returns the scientific mantissa and exponent.
When $x$ is positive, we can write $x = 2^{e_s}m_s$, where $e_s$ is an integer and $m_s$ is
a rational number with $1 \leq m_s < 2$. We represent the rational mantissa as a float. The
conversion might not be exact, so we round to the nearest float using the provided rounding
mode. If the rounding mode is Exact
but the conversion is not exact, None
is returned.
$$
f(x, r) \approx (\frac{x}{2^{\lfloor \log_2 x \rfloor}}, \lfloor \log_2 x \rfloor).
$$
Worst-case complexity
Constant time and additional memory.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::mantissa_and_exponent::*;
use malachite_base::num::conversion::traits::SciMantissaAndExponent;
use malachite_base::num::float::NiceFloat;
use malachite_base::rounding_modes::RoundingMode;
fn test<T: PrimitiveUnsigned, U: PrimitiveFloat>(
n: T,
rm: RoundingMode,
out: Option<(U, u64)>,
) {
assert_eq!(
sci_mantissa_and_exponent_with_rounding(n, rm).map(|(m, e)| (NiceFloat(m), e)),
out.map(|(m, e)| (NiceFloat(m), e))
);
}
test::<u32, f32>(3, RoundingMode::Down, Some((1.5, 1)));
test::<u32, f32>(3, RoundingMode::Ceiling, Some((1.5, 1)));
test::<u32, f32>(3, RoundingMode::Up, Some((1.5, 1)));
test::<u32, f32>(3, RoundingMode::Nearest, Some((1.5, 1)));
test::<u32, f32>(3, RoundingMode::Exact, Some((1.5, 1)));
test::<u32, f32>(123, RoundingMode::Floor, Some((1.921875, 6)));
test::<u32, f32>(123, RoundingMode::Down, Some((1.921875, 6)));
test::<u32, f32>(123, RoundingMode::Ceiling, Some((1.921875, 6)));
test::<u32, f32>(123, RoundingMode::Up, Some((1.921875, 6)));
test::<u32, f32>(123, RoundingMode::Nearest, Some((1.921875, 6)));
test::<u32, f32>(123, RoundingMode::Exact, Some((1.921875, 6)));
test::<u32, f32>(1000000000, RoundingMode::Nearest, Some((1.8626451, 29)));