Logo

Programming-Idioms

  • JS
  • Rust

Idiom #201 Euclidean norm

Calculate n, the Euclidean norm of data, where data is a list of floating point values.

use libm::sqrt;
fn euclidean(data: Vec<f64>) -> f64 {
    let mut n = 0.0;
    for i in data {
        n += i*i;
    }
    return sqrt(n as f64)
}
let n = euclidean(data);
const n = Math.hypot(...data)

Spread syntax requires ES6 or newer
var n = Math.hypot.apply(null, data)

If support for older browsers is necessary.
n = norm2( data )

data may be a multidimensional array (e.g. data(:,:)). n is the Frobenius norm if data is a 2-dimensional array (matrix).

New implementation...
< >
Bart