In keeping with the “There’s only one obvious way to do it”, how do you get the magnitude of a vector (1D array) in Numpy?
def mag(x):
return math.sqrt(sum(i**2 for i in x))
The above works, but I cannot believe that I must specify such a trivial and core function myself.
The function you’re after is
numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array — sayx.norm()— but oh well).You can also feed in an optional
ordfor the nth order norm you want. Say you wanted the 1-norm:And so on.