Skip to main content

25_normalize_vector/
25_normalize_vector.rs

1//! L2 normalisation of a vector using simple tensor operations.
2//!
3//! Run: cargo run --example 25_normalize_vector
4//!
5//! This example intentionally computes the norm via as_slice() so you can
6//! see how ordinary Rust and Tensor arithmetic compose for small PoC math.
7
8use matten::Tensor;
9
10/// Returns the L2 norm (Euclidean length) of a 1-D tensor.
11fn l2_norm(v: &Tensor) -> f64 {
12    v.as_slice().iter().map(|x| x * x).sum::<f64>().sqrt()
13}
14
15/// Returns the L2-normalised version of `v` (unit vector).
16fn normalize(v: &Tensor) -> Tensor {
17    let norm = l2_norm(v);
18    v / norm
19}
20
21fn main() {
22    let v = Tensor::from_vec(vec![3.0, 4.0]);
23    println!("v        = {:?}", v.as_slice());
24    println!("‖v‖      = {}", l2_norm(&v)); // 5.0
25
26    let u = normalize(&v);
27    println!("norm(v)  = {:?}", u.as_slice()); // [0.6, 0.8]
28
29    let norm_u = l2_norm(&u);
30    println!("‖norm(v)‖ = {norm_u:.6}"); // ≈ 1.0
31    assert!((norm_u - 1.0).abs() < 1e-10, "unit vector check failed");
32    println!("Unit vector check: OK");
33}