Function malachite_base::num::conversion::mantissa_and_exponent::from_sci_mantissa_and_exponent_round
source · pub fn from_sci_mantissa_and_exponent_round<T: PrimitiveUnsigned, U: PrimitiveFloat>(
sci_mantissa: U,
sci_exponent: u64,
rm: RoundingMode
) -> Option<(T, Ordering)>
Expand description
Constructs a primitive integer from its scientific mantissa and exponent. An Ordering
is
also returned, indicating whether the returned value is less than, equal to, or greater than the
exact value implied by the input.
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$. Here, the rational mantissa is provided as a float. If
the mantissa is outside the range $[1, 2)$, None
is returned.
Some combinations of mantissas and exponents do not specify an integer, in which case the
resulting value is rounded to an integer using the specified rounding mode. If the rounding mode
is Exact
but the input does not exactly specify an integer, None
is returned.
$$ f(x, r) \approx 2^{e_s}m_s. $$
§Worst-case complexity
Constant time and additional memory.
§Panics
Panics if sci_mantissa
is zero.
§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::rounding_modes::RoundingMode;
use std::cmp::Ordering;
use std::str::FromStr;
fn test<T: PrimitiveUnsigned, U: PrimitiveFloat>(
mantissa: U,
exponent: u64,
rm: RoundingMode,
out: Option<(T, Ordering)>,
) {
assert_eq!(
from_sci_mantissa_and_exponent_round::<T, U>(mantissa, exponent, rm),
out
);
};
test::<u32, f32>(1.5, 1, RoundingMode::Floor, Some((3, Ordering::Equal)));
test::<u32, f32>(1.5, 1, RoundingMode::Down, Some((3, Ordering::Equal)));
test::<u32, f32>(1.5, 1, RoundingMode::Ceiling, Some((3, Ordering::Equal)));
test::<u32, f32>(1.5, 1, RoundingMode::Up, Some((3, Ordering::Equal)));
test::<u32, f32>(1.5, 1, RoundingMode::Nearest, Some((3, Ordering::Equal)));
test::<u32, f32>(1.5, 1, RoundingMode::Exact, Some((3, Ordering::Equal)));
test::<u32, f32>(1.51, 1, RoundingMode::Floor, Some((3, Ordering::Less)));
test::<u32, f32>(1.51, 1, RoundingMode::Down, Some((3, Ordering::Less)));
test::<u32, f32>(1.51, 1, RoundingMode::Ceiling, Some((4, Ordering::Greater)));
test::<u32, f32>(1.51, 1, RoundingMode::Up, Some((4, Ordering::Greater)));
test::<u32, f32>(1.51, 1, RoundingMode::Nearest, Some((3, Ordering::Less)));
test::<u32, f32>(1.51, 1, RoundingMode::Exact, None);
test::<u32, f32>(2.0, 1, RoundingMode::Floor, None);
test::<u32, f32>(10.0, 1, RoundingMode::Floor, None);
test::<u32, f32>(0.5, 1, RoundingMode::Floor, None);