Skip to main content

l2_norm

Function l2_norm 

Source
pub fn l2_norm<T: RealScalar>(x: &[T]) -> T
Expand description

Computes the L2 norm (Euclidean norm) of a slice of real scalars.

Uses BLAS/LAPACK-style incremental scaling to prevent overflow and underflow. The algorithm maintains the invariant ||x||₂ = scale × √sumsq where all accumulated squared values are normalized to the range [0, 1].

§Arguments

§Returns

The L2 norm: $|x|_2 = \sqrt{\sum_i x_i^2}$

§Algorithm Complexity

  • Time: O(n) single-pass
  • Space: O(1)

§Examples

use num_valid::{RealNative64StrictFinite, RealScalar, algorithms::l2_norm::l2_norm};

// Pythagorean triple: 3² + 4² = 5²
let v = vec![
    RealNative64StrictFinite::from_f64(3.0),
    RealNative64StrictFinite::from_f64(4.0),
];
assert_eq!(*l2_norm(&v).as_ref(), 5.0);

// Empty slice returns zero
let empty: Vec<RealNative64StrictFinite> = vec![];
assert_eq!(*l2_norm(&empty).as_ref(), 0.0);

// Works with extreme values (no overflow)
let large = vec![
    RealNative64StrictFinite::from_f64(1e154),
    RealNative64StrictFinite::from_f64(1e154),
];
assert!(l2_norm(&large).as_ref().is_finite());