def norm(x, p=2): r""" Gives the entrywise `p`-norm of an iterable *x*, i.e. the vector norm `\left(\sum_k |x_k|^p\right)^{1/p}`, for any given `1 \le p \le \infty`. Special cases: If *x* is not iterable, this just returns ``absmax(x)``. ``p=1`` gives the sum of absolute values. ``p=2`` is the standard Euclidean vector norm. ``p=inf`` gives the magnitude of the largest element. For *x* a matrix, ``p=2`` is the Frobenius norm. For operator matrix norms, use :func:`mnorm` instead. You can use the string 'inf' as well as float('inf') or mpf('inf') to specify the infinity norm. **Examples** >>> from mpmath import * >>> mp.dps = 15 >>> x = matrix([-10, 2, 100]) >>> norm(x, 1) mpf('112.0') >>> norm(x, 2) mpf('100.5186549850325') >>> norm(x, inf) mpf('100.0') """ try: iter(x) except TypeError: return absmax(x) if type(p) is not int: p = mpmathify(p) if p == inf: return max(absmax(i) for i in x) elif p == 1: return fsum(x, absolute=1) elif p == 2: return sqrt(fsum(x, absolute=1, squared=1)) elif p > 1: return nthroot(fsum(abs(i)**p for i in x), p) else: raise ValueError('p has to be >= 1')
def mnorm_oo(A): """ Calculate the oo-norm (maximal row sum) of a matrix. """ assert isinstance(A, matrix) m, n = A.rows, A.cols return max((sum((absmax(A[i, j]) for j in xrange(n))) for i in xrange(m)))
def mnorm_oo(A): """ Calculate the oo-norm (maximal row sum) of a matrix. """ assert isinstance(A, matrix) m, n = A.rows, A.cols return max((sum((absmax(A[i,j]) for j in xrange(n))) for i in xrange(m)))
def mnorm_1(A): """ Calculate the 1-norm (maximal column sum) of a matrix. """ assert isinstance(A, matrix) m, n = A.rows, A.cols return max(fsum(absmax(A[i,j]) for i in xrange(m)) for j in xrange(n))
def norm_p(x, p=2): """ Calculate the p-norm of a vector. 0 < p <= oo Note: you may want to use float('inf') or mpmath's equivalent to specify oo. """ if p == inf: return max((absmax(i) for i in x)) elif p > 1: return nthroot(sum((abs(i)**p for i in x)), p) elif p == 1: return sum((abs(i) for i in x)) else: raise ValueError('p has to be an integer greater than 0')