Science/수학
[수학] python으로 유클리드 거리 계산하기
pbj0812
2020. 9. 7. 01:11
0. 목표
- python으로 유클리드 거리 계산하기
1. 기본 이론
- 링크
2. 실습
1) library 호출
import numpy as np
import pandas as pd
2) 제곱근 함수 제작
- 에러 발생시(입력값이 0인 경우) 결과값이 0으로 출력
def sqrt(inp):
result = inp/2
for i in range(30):
try:
result = (result + (inp / result)) / 2
except:
result = 0
return result
3) 유클리드거리 계산 함수 제작
- 이중 for문을 통하여 모든 리스트 값이 한번씩 마주치면서 유클리드 거리 계산을 한 뒤 데이터 프레임의 형태로 출력
def euclidean(inp):
result = []
len_inp = len(inp)
for i in inp:
for j in inp:
tmp = sqrt((i[0] - j[0])**2 + (i[1] - j[1])**2)
result.append(tmp)
result = np.array(result)
result = np.reshape(result, (len_inp, len_inp))
result = pd.DataFrame(result)
return result
4) 데이터 생성
data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
5) 실행
result = euclidean(data)
6) 결과
result
3. 참고
- 유클리드 거리