Skip to main content

primitive_float_log_base_2

Function primitive_float_log_base_2 

Source
pub fn primitive_float_log_base_2<T>(x: T) -> T
where Float: From<T> + PartialOrd<T>, for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float> + PrimitiveFloat,
Expand description

Computes the base-2 logarithm of a primitive float, $\log_2 x$.

This function is correctly rounded. The standard library’s log2 is correctly rounded for f32 but not always for f64, so for some f64 inputs this function is more accurate.

The base-2 logarithm of any nonzero negative number is NaN.

$$ f(x) = \log_2 x+\varepsilon. $$

  • If $\log_2 x$ is infinite, zero, or NaN, $\varepsilon$ may be ignored or assumed to be 0.
  • If $\log_2 x$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 |\log_2 x|\rfloor-p}$, where $p$ is precision of the output (typically 24 if T is a f32 and 53 if T is a f64, but less if the output is subnormal).

Special cases:

  • $f(\text{NaN})=\text{NaN}$
  • $f(\infty)=\infty$
  • $f(-\infty)=\text{NaN}$
  • $f(\pm0.0)=-\infty$
  • $f(x)=\text{NaN}$ for $x<0$

Neither overflow nor underflow is possible.

§Worst-case complexity

Constant time and additional memory.

§Examples

use malachite_base::num::basic::traits::NegativeInfinity;
use malachite_base::num::float::NiceFloat;
use malachite_float::arithmetic::log_base_2::primitive_float_log_base_2;

assert!(primitive_float_log_base_2(f32::NAN).is_nan());
assert_eq!(
    NiceFloat(primitive_float_log_base_2(f32::INFINITY)),
    NiceFloat(f32::INFINITY)
);
assert!(primitive_float_log_base_2(f32::NEGATIVE_INFINITY).is_nan());
assert_eq!(
    NiceFloat(primitive_float_log_base_2(0.0f32)),
    NiceFloat(f32::NEGATIVE_INFINITY)
);
assert_eq!(
    NiceFloat(primitive_float_log_base_2(8.0f32)),
    NiceFloat(3.0)
);
assert_eq!(
    NiceFloat(primitive_float_log_base_2(10.0f32)),
    NiceFloat(3.321928)
);
assert!(primitive_float_log_base_2(-10.0f32).is_nan());