g | x | w | all
Bytes Lang Time Link
097Go240607T205843Zbigyihsu
086Swift 5.9240311T185037ZmacOSist
3825R240311T104012Zint 21h
004Thunno 2230722T062721ZThe Thon
080Fortran GFortran230308T050818Zroblogic
035Juby221116T214810ZJordan
006Husk220111T144005ZNatte
018Factor + math.distances220111T074436Zchunes
026Desmos220111T070901ZAiden Ch
002Vyxal211217T063509Zlyxal
077C gcc180716T113237Zgastropn
032Haskell160612T194310ZRodrigo
008Stax180709T160521Zrecursiv
047Python 2160130T130637ZLogic Kn
044Python 3180411T202644Zxbarbie
004R170118T120841Zrturnbul
037JavaScript ES6160130T141542ZNeil
036Excel VBA171125T222535ZTaylor R
002Pyth160130T170420ZBlue
015TIBasic TI84 Plus CE171124T025709Zpizzapan
074Elixir171124T005954ZWalerian
276C170203T160216ZAbel Tom
105Java160130T212831Zბიმო
00405AB1E170117T193834ZMagic Oc
048Clojure170117T001739ZNikoNyrh
050Ruby160612T234332ZValue In
007Pyke160509T100345ZBlue
nanMathcad160425T115215ZStuart B
035Sage160425T072453Zuser4594
009J160205T184624ZGareth
024Perl 6160204T033628ZHotkeys
012Seriously160131T203735Zuser4594
002MATL160130T184502ZLuis Men
072C#160131T190743ZOlivia T
239AppleScript160131T142555ZAddison
070Python 3160130T212406ZTim
043golflua160131T134221ZKyle Kan
011APL160130T183936ZAlex A.
046Haskell160130T132337Zyyny
052Ruby160130T224149ZLevel Ri
004Jelly160130T130522ZDennis
062Scala160130T152304Zcorvus_1
016Julia160130T182910ZAlex A.
003MATL160130T142104Zflawr
008CJam160130T132201ZMartin E
613𝔼𝕊𝕄𝕚𝕟160130T171502ZMama Fun
015Octave160130T133951Zalephalp
011Mathematica160130T131346ZMartin E

Go, 97 bytes

import."math"
func f(p,q[]float64)(d float64){for i:=range p{d+=Pow(p[i]-q[i],2)}
return Sqrt(d)}

Attempt This Online!

Swift 5.9, 86 bytes

import Foundation
let f={(p:[(Double,_)])in
sqrt(p.map{pow($0.1-$0.0,2)}.reduce(0,+))}

Don't Try It Online, because TIO is too old. Here's a JDoodle link instead.

f is of type ([(Double, Double)]) -> Double -- it takes an array of pairs of coordinates, one per vector.

I just used the subtract-square-sum-squareRoot trick borrowed from other answers.

R, 38 bytes and 25 bytes

Sure, it is impossible to compete with the shortest 4 bytes answer, but I wanted to share anyway a hopefully interesting solution (38 bytes):

f=\(x,y)sd(c(x-y,y-x))*(nrow(x)-.5)^.5

How does it work? Standard deviation of a sample is calculated as a square root of the sum of squares of deviation scores divided by sample size minus one. enter image description here

The trick is to add to the sample a second set of the same numbers with the opposite sign (like c(1,2,-1,-2)). This way we get rid of mean (=0) out of the formula, but also we are getting each number twice. To obtain the sum of squares we only need to "neutralize" the term sqrt(2/(N-1)), whereby the sample size N is 2*N_dimensions.

...but unfortunately this bright =) solution sucks to the old good straightforward formula (25 bytes):

g=\(x,y)(sum((x-y)^2))^.5

Here is the result:

> list.x <- list(matrix(1),
+                matrix(c(1,1),2),
+                matrix(c(1,2),2),
+                matrix(c(1,2,3,4), 4),
+                matrix(c(1.5,2,-5), 3),
+                matrix(c(13.37,2,6,-7),4))
> 
> list.y <- list(matrix(3), 
+                matrix(c(1,1), 2),
+                matrix(c(3,4),2),
+                matrix(c(5,6,7,8),4),
+                matrix(c(-3.45,-13,145),3),
+                matrix(c(1.2,3.4,-5.6,7.89),4))
> 
> correct = list(2,0,2.82842712475,8,150.829382085,22.5020221314)
> 
> do.call(rbind, Map(\(x,y,z)c(f(x,y),g(x,y),z),list.x,list.y,correct))
           [,1]       [,2]       [,3]
[1,]   2.000000   2.000000   2.000000
[2,]   0.000000   0.000000   0.000000
[3,]   2.828427   2.828427   2.828427
[4,]   8.000000   8.000000   8.000000
[5,] 150.829382 150.829382 150.829382
[6,]  22.502022  22.502022  22.502022

Thunno 2, 4 bytes

-²Sƭ

Try it online!

Explanation

-²Sƭ  # Implicit input
-     # Subtract
 ²    # Square
  S   # Sum
   ƭ  # Square root
      # Implicit output

Fortran (GFortran), 85 80 bytes

function d(A,n);real A(n,2);s=0;do5 i=1,n;s=s+(A(i,1)-A(i,2))**2
5 d=sqrt(s);end

Try it online!   85 bytes

Instead of two vectors, I read all the data into two rows of array A. But Fortran 'helpfully' stores matrices by column so when I call the procedure A is transposed.
Using line number 5 instead of enddo saves 2 bytes :)
Saved 5 bytes using function instead of subroutine

J-uby, 35 bytes

+:zip|:*&(+:-|~:**&2)|:sum|~:**&0.5

Attempt This Online!

+:zip | :* & (+:- | ~:** & 2) | :sum | ~:** & 0.5

+:zip |                                            # Zip input arrays, then
        :* & (              )                      # map with
              +:- | ~:** & 2                       #   Difference, then square
                              | :sum |             # then sum, then
                                       ~:** & 0.5  # square root
                                

Husk, 6 bytes

√Σzo□-

Try it online!

Explanation

√Σzo□-
  z     zip input arguments
   o    with composed function
     -  difference
    □   squared
 Σ      sum
√       sqrt

Factor + math.distances, 18 bytes

euclidian-distance

Try it online!

Built-in.

Desmos, 26 bytes

f(a,b)=total((a-b)^2)^{.5}

The function \$f(a,b)\$ takes in two lists, \$a\$ and \$b\$, representing the two points, and returns the distance between them.

I think the code is pretty self explanatory, even for someone unfamiliar with Desmos.

Try It On Desmos!

Try It On Desmos! - Prettified

Vyxal, 2 bytes

∆d

Try it Online!

Laughs in built-in. Generalised euclidian distance do be like that sometimes.

C (gcc), 79 77 bytes

-2 bytes thanks to ceilingcat.

TIO requires compiler flag -lm. GCC of MinGW (that I use) does not.

f(p,q,d,s)float*p,*q,s;{for(s=0;d--;)s+=*p++*=*p-=*q++;printf("%f",sqrt(s));}

Try it online!

Haskell, 32 bytes

((sqrt.sum.map(^2)).).zipWith(-)

λ> let d = ((sqrt.sum.map(^2)).).zipWith(-)
λ> d [1] [3]
2.0
λ> d [1,1] [1,1]
0.0
λ> d [1,2] [3,4]
2.8284271247461903
λ> d [1..4] [5..8]
8.0
λ> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
λ> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522

Stax, 8 bytes

äÖ╙í▼=╬b

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

\       zip the coordinates into pairs
{       for each pair,
  :s    compute the absolute span
  J+    square and add to total
F       
|Q      square root result

Run this one

Python 2, 47 bytes

A straight forward solution. The function expects 2 points as sequences of numbers, and returns the distance between them.

lambda a,b:sum((d-e)**2for d,e in zip(a,b))**.5

Example:

>>> f([13.37, 2, 6, -7], [1.2, 3.4, -5.6, 7.89])
22.50202213135522

Python 3, 44 bytes

lambda*a:sum((x-y)**2for x,y in zip(*a))**.5

Try it online!

Ungolfed version:

      ₙ
sqrt( ∑(xᵢ - yᵢ)² )
     ⁱ⁼¹

def d(a, b):                    # two points (lists or tuples)
    return sum(                 # sum of...
        (x - y) ** 2            # (xᵢ - yᵢ)²
        for x,y in zip(a, b)    # 
    ) ** 0.5                    # square root of sum

R, 4 bytes

dist

This is a built-in function to calculate the distance matrix of any input matrix. Defaults to euclidean distance.

Example usage:

> x=matrix(c(1.5,-3.45,2,-13,-5,145),2)
> x
      [,1] [,2] [,3]
[1,]  1.50    2   -5
[2,] -3.45  -13  145
> dist(x)
         1
2 150.8294

If you're feeling disappointed because it's a built-in, then here's a non-built-in (or at least, it's less built-in...) version for 22 bytes (with thanks to Giuseppe):

pryr::f(norm(x-y,"F"))

This is an anonymous function that takes two vectors as input.

JavaScript ES7, 45 ES6, 37 bytes

a=>Math.hypot(...a.map(([b,c])=>b-c))

Expects an array of pairs of coordinates, one from each vector, e.g. [[1, 5], [2, 6], [3, 7], [4, 8]]. If that is unacceptable, then for 42 bytes:

(a,b)=>Math.hypot(...a.map((e,i)=>e-b[i]))

Expects two arrays of equal length corresponding to the two N-dimensional vectors, e.g. [1, 2, 3, 4], [5, 6, 7, 8]. Edit: Saved 3 bytes thanks to @l4m2. (Also, did nobody notice my typo?)

Excel VBA, 36 Bytes

Anonymous VBE immediate window function that takes input as two vectors, which are projected unto the range 1:2, and outputs to the VBE immediate window

[3:3]="=(A1-A2)^2":?[Sqrt(Sum(3:3))]

Pyth, 2 bytes

.a

.a - L2 norm of vector difference of A[0] and A[1].

Literally a function that does this problem

Try it here.

TI-Basic (TI-84 Plus CE), 15 bytes

Prompt A,B
√(sum((LA-LB)2

TI-Basic is a tokenized language.

Prompts for input as two lists, and returns the Euclidian distance betwrrn them in Ans

Explanation:

Prompt A,B    # 5 bytes, Prompts for two inputs; if the user inputs lists:
           # they are stored in LA and LB
√(sum((LA-LB)2 # 10 bytes, Euclidian distance between points
           #(square root of (sum of (squares of (differences of coordinates))))

Elixir, 74 bytes

:math.sqrt Enum.reduce Enum.zip(p,q),0,fn({a,b},c)->:math.pow(a-b,2)+c end

You can try it online

C 276 bytes

f(){*a,*b,d=0;l=1;a=malloc(sizeof(float)*50);b=malloc(sizeof(float)*50);scanf("%f",&a[0]);while(getchar()!='\n'){scanf("%f",&a[l]);l++;}l=1;scanf("%f",&b[0]);while(getchar()!='\n'){scanf("%f",&b[l]);l++;}for(int i=0;i<l;i++){d+=pow((a[i]-b[i]),2);}printf("%.5f",pow(d,0.5));}

Ungolfed version:

void f()
{

  float *a,*b,d=0;
  int l=1;

   a=malloc(sizeof(float)*50);
   b=malloc(sizeof(float)*50);

   //Accept p1,p2,p3.....pn
   scanf("%f",&a[0]);

   while(getchar()!='\n')
   {    
     scanf("%f",&a[l]);
     l++;
   }
   l=1;

   //Accept q1,q2,q3.....qn
   scanf("%f",&b[0]);
   while(getchar()!='\n')
  {    
    scanf("%f",&b[l]);
    l++;
  }

  for(int i=0;i<l;i++)
  {
    d+=pow((a[i]-b[i]),2);   
  }

  printf("\n%.5f",pow(d,0.5));
}

Pretty straightforward. This solution lets you measure distance between 2 points in upto 50 dimensions (can be increased).

In Cartesian coordinates, input the position of first point of n dimensions. (p1 p2 p3 ...pn) and press Enter.

Next, input the position of second point of n dimensions. (q1 q2 q3 ...qn) and press Enter to get the Euclidean Distance.

Java, 130 117 114 107 105 bytes

This is the obvious solution. I don't usually golf in Java, but I was curious to see if Java could beat the Brainfuck version. Doesn't seem like I did a good job then.. Maybe one could use the new Map/Reduce from Java 8 to save some bytes.

Thanks to @flawr (13 bytes), @KevinCruijssen (9 bytes) and @DarrelHoffman (3 bytes)!

Golfed:

double d(float[]a,float[]b){float x=0,s;for(int i=0;i<a.length;x+=s*s)s=a[i]-b[i++];return Math.sqrt(x);}

Ungolfed:

double d(float[] a, float[] b) {
  float x=0,s;

  for(int i=0; i<a.length; x+=s*s)
    s = a[i] - b[i++];

  return Math.sqrt(x);
}

05AB1E, 4 bytes

-nOt

Try it online!

Negative not y'all!

-    # a-b
 n   # (a-b)**2
  O  # sum((a-b)**2) for all a,b
   t # sqrt(sum((a-b)**2) for all a,b)

Clojure, 48 bytes

#(Math/sqrt(apply +(for[d(map - % %2)](* d d))))

Ruby, 50 bytes

Zip, then map/reduce. Barely edges out the other Ruby answer from @LevelRiverSt by 2 bytes...

->p,q{p.zip(q).map{|a,b|(a-b)**2}.reduce(:+)**0.5}

Try it online

Pyke, 7 bytes

,A-MXs,

Try it here!

Transpose, apply subtract, map square, sum, sqrt.

Mathcad, bytes

enter image description here

Uses the built-in vector magnitude (absolute value) operator to calculate the size of the difference between the two points (expressed as vectors).


Mathcad golf size on hold until I get (or somebody else gets) round to opening up the discussion on meta. However, the shortest way (assuming that input of the point vectors doesn't contribute to the score) is 3 "bytes" , with 14 bytes for the functional version.

Sage, 35 bytes

lambda a,b,v=vector:norm(v(a)-v(b))

This function takes 2 lists as input and returns a symbolic expression. The distance is calculated by performing vector subtraction on the lists and computing the Euclidean norm of the resultant vector.

Try it online

J, 9 bytes

+&.*:/-/>

This is a function that takes one set of coordinates from the other (-/>), and then performs a sum + under &. square *:.

The input should be in the format x y z;a b c where x y z is your first set of co-ordinates and a b c is the other.

Perl 6, 30 29 26 24 bytes

{sqrt [+] ([Z-] $_)»²}

(Thanks @b2gills for 2 more bytes lost)

usage

my &f = {sqrt [+] (@^a Z-@^b)»²};

say f([1], [3]); # 2
say f([1,1], [1,1]); # 0
say f([1,2], [3,4]); # 2.82842712474619
say f([1,2,3,4], [5,6,7,8]); # 8
say f([1.5,2,-5], [-3.45,-13,145]); # 150.829382084526
say f([13.37,2,6,-7], [1.2,3.4,-5.6,7.89]); # 22.5020221313552

Seriously, 12 bytes

,iZ`i-ª`MΣ√A

Try it online!

Explanation:

,iZ`i-ª`MΣ√A
,iZ           get input, flatten, zip
   `   `M     map:
    i-ª         flatten, subtract, square
         Σ√A  sum, sqrt, abs

MATL, 2 bytes

ZP

Try it online!

The ZP function (corresponding to MATLAB's pdist2) computes all pairwise distances between two sets of points, using Euclidean distance by default. Each set of points is a matrix, and each point is a row. In this case it produces a single result, which is the distance between the two points.

C#, 72 bytes

(float[]i,float[]n)=>System.Math.Sqrt(i.Zip(n,(x,y)=>(x-y)*(x-y)).Sum())

A simple solution using Linq.

AppleScript, 241 239 bytes

This is golfed code, but I've put comments in in the form --.

on a()    -- Calling for getting input
set v to{1}          -- Arbitrary placeholder
repeat until v's item-1=""       -- Repeat until no input is gathered
set v to v&(display dialog""default answer"")'s text returned   -- Add input to list
end      -- End the repeat
end      -- End the method
set x to a()   -- Set the array inputs
set y to a()
set z to 0     -- Sum placeholder
set r to 2     -- 2 is the first significant array index
repeat(count of items in x)-2     -- Loop through all but first and last of the array
set z to z+(x's item r-y's item r)^2    -- Add the square of the difference
end   -- End the repeat
z^.5  -- Return the square root of the sum

This uses the same algorithm as most of the other programs here.

run sample

Python 3, 70 Chars

Loops through, finding the square of the difference and then the root of the sum:

a=input()
b=input()
x=sum([(a[i]-b[i])**2 for i in range(len(a))])**.5

golflua, 43 chars

\d(x,y)s=0~@i,v i(x)s=s+(v-y[i])^2$~M.q(s)$

Works by calling it as

> w(d({1,1},{1,1}))
0
> w(d({1,2},{3,4}))
2.82842712475
> w (d({1,2,3,4},{5,6,7,8}))
8

A Lua equivalent would be

function dist(x, y)
    s = 0
    for index,value in ipairs(x)
       s = s + (value - y[index])^2
    end
    return math.sqrt(s)
end

APL, 14 11 bytes

.5*⍨(+/-×-)

This is dyadic function train that takes the vectors on the left and right and returns the Euclidean norm of their difference.

Explanation:

       -×-)  ⍝ Squared differences
    (+/      ⍝ Sum them
.5*⍨         ⍝ Take the square root

Try it here

Saved 3 bytes thanks to Dennis!

Haskell, 46 bytes

d :: Floating c => [c] -> [c] -> c
d a=sqrt.sum.map((^2).uncurry(flip(-))).zip a

Haskell, 35 bytes (By @nimi)

d :: Float c => [c] -> [c] -> c
d a=sqrt.sum.zipWith(((^2).).(-))a

Haskell, 31 bytes

Like this Scala answer, takes input as a sequence of tuples

<hack>

d :: Float c => [(c,c)] -> c
d=sqrt.sum.map$(^2).uncurry(-)

</hack>

Examples:

Prelude> d [1] [3]
2.0
Prelude> d [1,1] [1,1]
0.0
Prelude> d [1,2,3,4] [5,6,7,8]
8.0
Prelude> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
Prelude> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522

Ruby, 52

->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}

In test program

f=->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}

p f[[1], [3]] # 2
p f[[1,1], [1,1]] # 0
p f[[1,2], [3,4]] # 2.82842712475
p f[[1,2,3,4], [5,6,7,8]] # 8
p f[[1.5,2,-5], [-3.45,-13,145]] # 150.829382085
p f[[13.37,2,6,-7], [1.2,3.4,-5.6,7.89]] # 22.5020221314

Jelly, 4 bytes

_²S½

Try it online!

How it works

_²S½    Main link. Left input: A (list). Right input: B (list).

_       Subtract B from A, element by element.
 ²      Square all differences.
  S     Add all squares.
   ½    Take the square root of the sum.

Scala, 67 62 bytes

def e(a:(Int,Int)*)=math.sqrt(a map(x=>x._2-x._1)map(x=>x*x)sum)

Requires input as a sequence/vector of var-arg tuples
Example:

scala> e((1, 5), (2, 6), (3, 7), (4, 8))
res1: Double = 8.0

Julia, 16 bytes

N(x,y)=norm(x-y)

This is a function that accepts two arrays and returns the Euclidean norm of their difference as a float.

You can verify all test cases at once online here.

MATL, 4.0 3 bytes

Thanks for -1 by @AndrasDeak!

-Zn

Reads two vectors (via implicit input that is requested by -) then substracts those and calculates the norm of their difference with Zn.

Try it Online!

CJam, 11 8 bytes

Thanks to Dennis for saving 3 bytes.

q~.-:mhz

Run all test cases.

Explanation

q~   e# Read and evaluate input.
.-   e# Vectorised difference.
:mh  e# Reduce √(x²+y²) over the list.
z    e# Take abs() to handle 1D input.

See this tip for why :mh works.

𝔼𝕊𝕄𝕚𝕟, 6 chars / 13 bytes

МŰМŷ…ï

Try it here (Firefox only).

Calculates norm of difference of input arrays.

Octave, 15 bytes

@(x,y)norm(x-y)

Example:

octave:1> d=@(x,y)norm(x-y);
octave:2> d([13.37,2,6,-7], [1.2,3.4,-5.6,7.89])
ans =  22.502

Mathematica, 11 bytes

Norm[#-#2]&

Input as two lists, output as a number. If the input is exact (integers, rationals, etc.) the output will be exact as well. If the input contains a floating-point number, the output will be a float as well.