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

6
  • Does Python offer vectors or SIMD? Commented Nov 10, 2020 at 1:06
  • @xxh sorry I don't really know what a SIMD is so can't answer your question, but apparently yes? stackoverflow.com/questions/44944367/… Commented Nov 10, 2020 at 1:09
  • 1
    The answers to that So question give an affirmative, "yes," and that means that the currently accepted answer is incredibly efficient. Commented Nov 10, 2020 at 1:11
  • 2
    @xxh - Only with modules like numpy or similar numeric modules. Commented Nov 10, 2020 at 1:11
  • 2
    @xxh - usually numpy is vectorized using a BLAS library and fast enough. But lacks gpu support and latest algorithmic optimizations. Commented Nov 10, 2020 at 1:16

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

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
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]

1 Comment

Wow, just one line of code! Wow thank you so much, I'm still pretty new to python :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.