【发布时间】:2020-11-10 00:53:04
【问题描述】:
我有密码
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
【问题讨论】:
-
Python 是否提供向量或 SIMD?
-
@xxh 抱歉,我真的不知道 SIMD 是什么,所以无法回答您的问题,但显然是的? stackoverflow.com/questions/44944367/…
-
So 问题的答案是肯定的,“是”,这意味着当前接受的答案非常有效。
-
@xxh - 仅适用于
numpy之类的模块或类似的数字模块。 -
@xxh - 通常
numpy使用BLAS 库进行矢量化并且足够快。但缺乏 gpu 支持和最新的算法优化。
标签: arrays numpy broadcasting