Arrays 无for循环的阵列广播
我有密码Arrays 无for循环的阵列广播,arrays,numpy,broadcasting,Arrays,Numpy,Broadcasting,我有密码 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]]) r
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循环。
谢谢你:这和你的计算一样。Python的
math
模块是不需要的
np.sqrt(((pos - ref)**2).sum(1))
输出:
你的方程实际上是
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])
哇,就一行代码!哇,非常感谢你,我对python还是很陌生:DDoes python提供向量还是SIMD?@xxh抱歉,我不知道SIMD是什么,所以无法回答你的问题,但显然是的?这个问题的答案是肯定的,“是的”,这意味着目前被接受的答案非常有效。@xxh-仅适用于
numpy
或类似的数字模块。@xxh-通常numpy
使用库进行矢量化,速度足够快。但是缺少gpu支持和最新的算法优化。哇,我从来没有真正使用过np.linalg.norm。我以前没看过,但谢谢你让我知道。看起来我应该做一些研究:D
dist_arr = np.linalg.norm(pos-ref, axis=1)
Out[14]:
array([1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862,
0.14142136])