normalize_simd

Function normalize_simd 

Source
pub fn normalize_simd<F>(x: &ArrayView1<'_, F>) -> Array1<F>
where F: Float + SimdUnifiedOps,
Expand description

Normalize a 1D array to unit length using L2 norm (SIMD-accelerated).

Computes x / ||x||₂ where ||x||₂ is the Euclidean (L2) norm. The resulting vector will have unit length (norm = 1).

§Arguments

  • x - Input 1D array to normalize

§Returns

Array1<F> with the same length as input, normalized to unit length. Returns zero array if input norm is zero or NaN.

§Performance

  • SIMD: Automatically used for large arrays (1000+ elements)
  • Scalar: Used for small arrays or when SIMD unavailable
  • Speedup: 2-4x for large f32 arrays on AVX2 systems

§Mathematical Definition

normalize(x) = x / ||x||₂
where ||x||₂ = sqrt(Σ xᵢ²)

§Examples

use scirs2_core::ndarray::array;
use scirs2_core::ndarray_ext::preprocessing::normalize_simd;

// 3-4-5 triangle
let x = array![3.0_f64, 4.0];
let result = normalize_simd(&x.view());

// norm = sqrt(9 + 16) = 5
// result = [3/5, 4/5] = [0.6, 0.8]
assert!((result[0] - 0.6_f64).abs() < 1e-10);
assert!((result[1] - 0.8_f64).abs() < 1e-10);

// Verify unit norm
let norm: f64 = result.iter().map(|x| x * x).sum::<f64>().sqrt();
assert!((norm - 1.0_f64).abs() < 1e-10);

§Edge Cases

  • Empty array: Returns empty array
  • Zero vector: Returns zero array (undefined normalization)
  • Single element: Returns array with single element ±1
  • NaN values: Returns zero array

§Applications

  • Machine Learning: Feature scaling for algorithms sensitive to magnitude
  • Cosine Similarity: Prerequisite for efficient similarity computation
  • Direction Vectors: Unit direction vectors in physics/graphics
  • Text Processing: TF-IDF normalization in NLP
  • Signal Processing: Normalized cross-correlation