Function fixed_ln

Source
fn fixed_ln<T>(x: &T) -> Option<T>
where T: FixedPointNumber + Copy + PartialOrd + FixedPointInfo, T::Inner: From<u8> + Shr<u32, Output = T::Inner> + TryInto<i128> + Copy,
Expand description

Computes the natural logarithm ln(x) for a fixed-point number.

§Algorithm

Uses repeated square root range reduction to bring x near 1, then evaluates ln via the series expansion in ln_near_one:

ln(x) = 2^k * ln(y)

where y is the range-reduced value near 1 and k is the number of square root reductions applied. The scaling back is done with a single multiply by 2^k to avoid accumulated rounding error from repeated multiplication.

§Domain

  • Defined only for x > 0. Returns None for x <= 0.
  • On unsigned types (FixedU64, FixedU128), ln(x) for x < 1 produces a negative result which is unrepresentable. Returns None in this case rather than silently returning a wrong answer. Use a signed type (FixedI64, FixedI128) if ln of fractional values is needed.

§Arguments

  • x - The fixed-point number to compute the natural logarithm of.

§Returns

  • Some(ln(x)) for valid inputs
  • None for x <= 0
  • None for unsigned types where x < 1 (result not representable)

§Examples

let x = FixedU64::saturating_from_integer(1);
assert_eq!(fixed_ln(&x), Some(FixedU64::zero())); // ln(1) = 0

let x = FixedU64::saturating_from_integer(2);
let result = fixed_ln(&x).unwrap();
// result ~= 0.693147180

// Negative input - always None
let x = FixedI64::saturating_from_integer(-1);
assert_eq!(fixed_ln(&x), None);

// Fractional input on unsigned type - None (unrepresentable result)
let x = FixedU64::saturating_from_rational(1, 2);
assert_eq!(fixed_ln(&x), None);

// Fractional input on signed type - correct negative result
let x = FixedI64::saturating_from_rational(1, 2);
let result = fixed_ln(&x).unwrap();
// result ~= -0.693147180