[Numpy-discussion] efficient norm of a vector
Bill Baxter
wbaxter at gmail.com
Wed Mar 14 01:54:57 EDT 2007
There is numpy.linalg.norm.
Here's what it does:
def norm(x, ord=None):
x = asarray(x)
nd = len(x.shape)
if ord is None: # check the default case first and handle it immediately
return sqrt(add.reduce((x.conj() * x).ravel().real))
if nd == 1:
if ord == Inf:
return abs(x).max()
elif ord == -Inf:
return abs(x).min()
elif ord == 1:
return abs(x).sum() # special case for speedup
elif ord == 2:
return sqrt(((x.conj()*x).real).sum()) # special case for speedup
else:
return ((abs(x)**ord).sum())**(1.0/ord)
elif nd == 2:
if ord == 2:
return svd(x, compute_uv=0).max()
elif ord == -2:
return svd(x, compute_uv=0).min()
elif ord == 1:
return abs(x).sum(axis=0).max()
elif ord == Inf:
return abs(x).sum(axis=1).max()
elif ord == -1:
return abs(x).sum(axis=0).min()
elif ord == -Inf:
return abs(x).sum(axis=1).min()
elif ord in ['fro','f']:
return sqrt(add.reduce((x.conj() * x).real.ravel()))
else:
raise ValueError, "Invalid norm order for matrices."
else:
raise ValueError, "Improper number of dimensions to norm."
--bb
On 3/14/07, lorenzo bolla <lbolla at gmail.com> wrote:
> Hi all,
> just a quick (and easy?) question.
> what is the best (fastest) way to implement the euclidean norm of a vector,
> i.e. the function:
>
> import scipy as S
> def norm(x):
> """normalize a vector."""
> return S.sqrt(S.sum(S.absolute(x)**2))
>
> ?
>
> thanks in advance,
> Lorenzo.
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
>
More information about the NumPy-Discussion
mailing list