# Distance between two points in n-dimensional space

Here is another simple one:

# The Challenge

Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.

• The coordinates will be rational numbers; the only limits are the restrictions of your language.
• Lowest dimension is 1, highest is whatever your language can handle
• You may assume that the two points are of the same dimension and that there will be no empty input.
• The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.

# Rules

• As usual, function or full program allowed.
• Input may be taken from STDIN, command line- or function arguments.
• Input format is up to you, specify which one you used in your answer.
• Output may be provided by printing to stdout or return value.
• This is so lowest byte-count wins! In case of a tie, the earlier answer wins.

# Test cases

Each point is represented by a list of length n.

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


Happy Coding!

• I'll give brainfuck a shot. Let's see what horrible monster comes out.
– yyny
Jan 30, 2016 at 12:56
• I assume you mean the Euclidean distance? Jan 30, 2016 at 13:54
• @flawr Yep, exactly. Just wanted to keep the title simple, since not everyone might know what that is at first glance. Could definetly write that in the challange tho :) Jan 30, 2016 at 14:02
• @DenkerAffe is it OK to return the distance squared if "your programming language does not support floating points"? This would make my brainfuck program a lot more accurate (Otherwise I'll have to implement some sort of estimation algorithm).
– yyny
Jan 30, 2016 at 14:58
• @DenkerAffe I think it's safe to say that brainfuck will never win a code golf. But it's just for fun anyways :)
– yyny
Jan 30, 2016 at 16:17

# 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))))


# 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.

• function(x,y)norm(x-y,"F") is shorter than your second version. Apr 11, 2018 at 15:56

# 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


# 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

# 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

# Husk, 6 bytes

√Σzo□-


Try it online!

### Explanation

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


# 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

• Drop a few more: sum([(x-y)**2 for x,y in zip(a,b)])**.5 Jan 31, 2016 at 4:55

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.

## Pyke, 7 bytes

,A-MXs,


Try it here!

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

# 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

## 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.

# 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))]


# Factor + math.distances, 18 bytes

euclidian-distance


Try it online!

Built-in.

# 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



# 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


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

• If only the IMSL library was installed on TIO. I could have used the DISL2 function. Mar 8, 2023 at 9:28

# Thunno 2, 4 bytes

-²Sƭ


Try it online!

#### Explanation

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


# 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.