Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #201 Euclidean norm

Calculate n, the Euclidean norm of data (an array or list of floating point values).

func Euclidean(data []float64) float64 {
	n := 0.0
	for _, val := range data {
		n += val * val
	}
	return math.Sqrt(n)
n = norm2( data )
const n = Math.hypot(...data)
var n = Math.hypot.apply(null, data)
double n = 0d;
for(double value : data) {
	n += value * value;
}
n = Math.sqrt(n);
uses math;
var
  data: array of double;
...
  n := norm(data);
...
use Math::GSL::Vector qw();
use Math::GSL::BLAS qw(gsl_blas_dnrm2);
my $data = [5.0, 4.0, 3.0, 2.0, 1.0];
my $n = gsl_blas_dnrm2(Math::GSL::Vector->new($data)->raw);
import numpy as np
np.linalg.norm(adata2[:, 0:3] - adata1[ipc1, 0:3], axis=1)
import numpy as np
n = np.linalg.norm(data)
require 'matrix'
data = Vector[5.0, 4.0, 3.0, 2.0, 1.0]
n = data.norm
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);
data := #( 5 4 3 2 1 ).
n := data squared sum sqrt.

New implementation...
< >
Bart