【问题标题】:Array Broadcasting without for loop没有 for 循环的数组广播
【发布时间】: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


【解决方案1】:

您的方程实际上是posref 之间的欧式距离。您可以使用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])

【讨论】:

  • 哇,我从来没有真正使用过 np.linalg.norm。以前没见过,但谢谢你让我知道。看起来我应该对它做一些研究:D
【解决方案2】:

这与您的计算相同。不需要 Python 的 math 模块。

np.sqrt(((pos - ref)**2).sum(1))

输出:

[1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862, 0.14142136]

【讨论】:

  • 哇,只有一行代码!哇,非常感谢,我对 python 还是很陌生:D
猜你喜欢
  • 1970-01-01
  • 2020-05-12
  • 2017-09-27
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 2017-02-20
  • 1970-01-01
相关资源
最近更新 更多