Search code examples
pythonlist3dgps

How to calculate distance without numpy


 myList =  [[0, 0, 0], #0
       [6.888437030500963, 5.159088058806049, -1.5885683833831], #1
       [2.0667720363602307, 5.384582486178219, -3.4898856343748133], #2
       [7.742743817055683, 1.4508370077567676,-3.957946551327696],#3
       [9.410384606156306, 9.613094711663472, -3.864209434979891],#4
       [5.047141494150383, 14.72917879480795, -1.4968295014732576],#5
       [0.05726832139919402,22.924103914172754, 8.158880019279806],#6
       [6.261613041330982, 30.96742292296441,4.361831405666459], #7
       [10.858248006533554, 38.94418868232428, 8.041510043975286],#8
       [10.30110231558782, 30.958212843691598, 6.724946753050958],#9
       [12.518841784463852,39.21843390844956, 16.057074108466132]]#10

import math

def distance (myList):

    dist = math.sqrt ((xa-xb)**2 + (ya-yb)**2 + (za-zb)**2)
    return dist

print("Distance:",(distance(myList)))

How can I calculate the distance of all that points but without NumPy? I understand how to do it with 2 but not with more than 2


Solution

  • We can find the euclidian distance with the equation: d = sqrt((px1 - px2)^2 + (py1 - py2)^2 + (pz1 - pz2)^2)

    Implementing in python:

    import math
    
    def dist(list):
      cummulativeDist = 0
    
      # iterate over sets of points
      for i in range(len(list) - 1):
        coordInit = list[i]
        coordFinal = list[i+1]
    
        # distance from one pt to the next
        dist = math.sqrt(((coordInit[0] - coordFinal[0]) ** 2) 
                        + ((coordInit[1] - coordFinal[2]) ** 2) 
                        + ((coordInit[2] - coordFinal[2]) ** 2)) 
    
        cummulativeDist += dist
    
      return cummulativeDist
    
    print(f"Distance: {dist(myList)}")
    

    This will take the 3 dimensional distance and from one point to the next and return the total distance traveled.