for 루프없이 어레이 브로드 캐스팅
Nov 10 2020
나는 코드가있다
import numpy as np
import math
pos = np.array([[ 1.72, 2.56],
[ 0.24, 5.67],
[ -1.24, 5.45],
[ -3.17, -0.23],
[ 1.17, -1.23],
[ 1.12, 1.08]])
ref = np.array([1.22, 1.18])
# Insert your solution below
d1 = math.sqrt((pos[0,0]-ref[0])**2 + (pos[0,1]-ref[1])**2)
d2 = math.sqrt((pos[1,0]-ref[0])**2 + (pos[1,1]-ref[1])**2)
d3 = math.sqrt((pos[2,0]-ref[0])**2 + (pos[2,1]-ref[1])**2)
d4 = math.sqrt((pos[3,0]-ref[0])**2 + (pos[3,1]-ref[1])**2)
d5 = math.sqrt((pos[4,0]-ref[0])**2 + (pos[4,1]-ref[1])**2)
d6 = math.sqrt((pos[5,0]-ref[0])**2 + (pos[5,1]-ref[1])**2)
예상되는 대답은
# [ 1.468, 4.596, 4.928 , 4.611, 2.410, 0.141 ]
for 루프를 사용하지 않고도 내 솔루션을 더 효율적이고 짧게 만들 수 있습니까? 감사합니다 : D
답변
2 MichaelSzczesny Nov 10 2020 at 07:59
이것은 계산과 동일합니다. Python의 math모듈은 필요하지 않습니다.
np.sqrt(((pos - ref)**2).sum(1))
밖:
[1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862, 0.14142136]
4 AndyL. Nov 10 2020 at 08:17
방정식은 실제로 pos와 사이의 유클리드 거리 ref입니다. 방정식을 추가로 단순화 할 수 있습니다.np.linalg.norm
dist_arr = np.linalg.norm(pos-ref, axis=1)
Out[14]:
array([1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862,
0.14142136])