2

I have the code

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)

The expected answer is

# [ 1.468,  4.596,  4.928 ,  4.611,  2.410,  0.141 ]

Is it possible to make my solution more efficient and short, preferably without the use of a for-loop. Thank you :D

Barry
  • 27
  • 5
  • Does Python offer vectors or SIMD? –  Nov 10 '20 at 01:06
  • @xxh sorry I don't really know what a SIMD is so can't answer your question, but apparently yes? https://stackoverflow.com/questions/44944367/are-numpys-basic-operations-vectorized-i-e-do-they-use-simd-operations – Barry Nov 10 '20 at 01:09
  • 1
    The answers to that So question give an affirmative, "yes," and that means that the currently accepted answer is incredibly efficient. –  Nov 10 '20 at 01:11
  • 2
    @xxh - Only with modules like `numpy` or similar numeric modules. – Michael Szczesny Nov 10 '20 at 01:11
  • @MichaelSzczesny Yes, that's what I had presumed, does Python offer vectors/SIMD via importing lower-level code, and out of what little I know about Python, I know that NumPy certainly wasn't written in Python, thus why I asserted that your answer was efficient, as it likely performs vectorized operations. –  Nov 10 '20 at 01:13
  • 2
    @xxh - usually `numpy` is vectorized using a [BLAS](https://stackoverflow.com/questions/37184618/find-out-if-which-blas-library-is-used-by-numpy) library and fast enough. But lacks gpu support and latest algorithmic optimizations. – Michael Szczesny Nov 10 '20 at 01:16

2 Answers2

3

Your equation is actually euclidean distance between pos and ref. You may simplify your equation further with 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])
Andy L.
  • 24,909
  • 4
  • 17
  • 29
  • 1
    wow, I've never really used np.linalg.norm. Haven't seen it before but thank you for letting me know. Looks like I should do a bit of research on it :D – Barry Nov 10 '20 at 01:28
1

This does the same as your computations. Python's math module is not needed.

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

Out:

[1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862, 0.14142136]
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32