Why only 2D and 3D? The universe may contain any number of dimensions! Most popular teories say there are around 6.
Since we are not sure of how many, lets use as backend a function that will work for any number of dimensions: distanceND.
from math import sqrt, pow # calculate the distance between two points in 2d,3d ... nD def distanceND(pA, pB, nD = None): dist = 0 # if a number of dimension was not specified, use the smalest number of dimensions if nD is None: nD = min(len(pA),len(pB)) for i in range(nD): dist += pow(pA[i] - pB[i], 2); return(sqrt(dist)); def distance2D(pA, pB): return(distanceND(pA, pB)) def distance3D(pA, pB): return(distanceND(pA, pB))
from math import sqrt- from math import sqrt, pow
- # calculate the distance between two points in 2d,3d ... nD
- def distanceND(pA, pB, nD = None):
- dist = 0
- # if a number of dimension was not specified, use the smalest number of dimensions
- if nD is None:
- nD = min(len(pA),len(pB))
- for i in range(nD):
- dist += pow(pA[i] - pB[i], 2);
- return(sqrt(dist));
- def distance2D(pA, pB):
if pA == pB: return 0(xA, yA), (xB, yB) = pA, pBreturn sqrt((xA - xB)**2 + (yA - yB)**2)- return(distanceND(pA, pB))
- def distance3D(pA, pB):
if pA == pB: return 0(xA, yA, zA), (xB, yB, zB) = pA, pBreturn sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2)- return(distanceND(pA, pB))