[파이썬] 두 점사이의 거리 구하기 코드

2020. 3. 28. 11:28노트/Python : 프로그래밍

# 피타고라스 정리를 이용한, 두 점 사이의 거리 구하기 코드 

 

 

2차원 공간

https://m.blog.naver.com/galaxyenergy/221263626715

import math

def pointDist(x1,y1,x2,y2):
    class Point2D:
        def __init__(self,x,y):
            self.x=x
            self.y=y
    p1=Point2D(x=x1,y=y1)
    p2=Point2D(x=x2,y=y2)
    print("p1:({},{})".format(p1.x, p1.y))
    print("p2:({},{})".format(p2.x, p2.y))
    dist=math.sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2))
    print(dist)
pointDist(30,20,50,40)

>> p1:(30,20)
>> p2:(50,40)
>> 28.284271247461902

 

 

3차원 공간 

https://m.blog.naver.com/galaxyenergy/221263626715

def pointDist(x1,y1,z1,x2,y2,z2):
    class Point3D:
        def __init__(self,x,y,z):
            self.x=x
            self.y=y
            self.z=z
    p1=Point3D(x=x1,y=y1,z=z1)
    p2=Point3D(x=x2,y=y2,z=z2)
    print("p1:({},{},{})".format(p1.x, p1.y, p1.z))
    print("p2:({},{},{})".format(p2.x, p2.y, p2.z))
    dist=math.sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2)+pow(p2.z-p1.z,2))
    print(dist)
pointDist(30,20,10,50,60,40)

>> p1:(30,20,10)
>> p2:(50,60,40)
>> 53.85164807134504