您如何获得Numpy中向量的大小? [英] How do you get the magnitude of a vector in Numpy?
本文介绍了您如何获得Numpy中向量的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与只有一种明显的方法"相一致,如何在Numpy中获得矢量(一维数组)的大小?
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 -- say x.norm()
-- but oh well).
import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)
您还可以输入所需的n阶范数的可选ord
.假设您想要1个标准:
You can also feed in an optional ord
for the nth order norm you want. Say you wanted the 1-norm:
np.linalg.norm(x,ord=1)
以此类推.
这篇关于您如何获得Numpy中向量的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文