~jtaylor/ubuntu/precise/python-numpy/multiarch-fix-818867

« back to all changes in this revision

Viewing changes to numpy/linalg/linalg.py

  • Committer: Bazaar Package Importer
  • Author(s): Sandro Tosi
  • Date: 2010-10-07 10:19:13 UTC
  • mfrom: (7.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20101007101913-8b1kmt8ho4upcl9s
Tags: 1:1.4.1-5
* debian/patches/10_use_local_python.org_object.inv_sphinx.diff
  - fixed small typo in description
* debian/patches/changeset_r8364.diff
  - fix memory corruption (double free); thanks to Joseph Barillari for the
    report and to Michael Gilbert for pushing resolution; Closes: #581058

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
        isfinite, size
21
21
from numpy.lib import triu
22
22
from numpy.linalg import lapack_lite
23
 
from numpy.core.defmatrix import matrix_power
 
23
from numpy.matrixlib.defmatrix import matrix_power
24
24
 
25
25
fortran_int = intc
26
26
 
27
27
# Error object
28
28
class LinAlgError(Exception):
 
29
    """
 
30
    Generic Python-exception-derived object raised by linalg functions.
 
31
 
 
32
    General purpose exception class, derived from Python's exception.Exception
 
33
    class, programmatically raised in linalg functions when a Linear
 
34
    Algebra-related condition would prevent further correct execution of the
 
35
    function.
 
36
 
 
37
    Parameters
 
38
    ----------
 
39
    None
 
40
 
 
41
    Examples
 
42
    --------
 
43
    >>> from numpy import linalg as LA
 
44
    >>> LA.inv(np.zeros((2,2)))
 
45
    Traceback (most recent call last):
 
46
      File "<stdin>", line 1, in <module>
 
47
      File "...linalg.py", line 350,
 
48
        in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
 
49
      File "...linalg.py", line 249,
 
50
        in solve
 
51
        raise LinAlgError, 'Singular matrix'
 
52
    numpy.linalg.linalg.LinAlgError: Singular matrix
 
53
 
 
54
    """
29
55
    pass
30
56
 
31
57
def _makearray(a):
32
58
    new = asarray(a)
33
 
    wrap = getattr(a, "__array_wrap__", new.__array_wrap__)
 
59
    wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
34
60
    return new, wrap
35
61
 
36
62
def isComplexType(t):
127
153
 
128
154
def tensorsolve(a, b, axes=None):
129
155
    """
130
 
    Solve the tensor equation a x = b for x
 
156
    Solve the tensor equation ``a x = b`` for x.
131
157
 
132
 
    It is assumed that all indices of x are summed over in the product,
133
 
    together with the rightmost indices of a, similarly as in
134
 
    tensordot(a, x, axes=len(b.shape)).
 
158
    It is assumed that all indices of `x` are summed over in the product,
 
159
    together with the rightmost indices of `a`, as is done in, for example,
 
160
    ``tensordot(a, x, axes=len(b.shape))``.
135
161
 
136
162
    Parameters
137
163
    ----------
138
 
    a : array_like, shape b.shape+Q
139
 
        Coefficient tensor. Shape Q of the rightmost indices of a must
140
 
        be such that a is 'square', ie., prod(Q) == prod(b.shape).
141
 
    b : array_like, any shape
142
 
        Right-hand tensor.
143
 
    axes : tuple of integers
144
 
        Axes in a to reorder to the right, before inversion.
 
164
    a : array_like
 
165
        Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
 
166
        the shape of that sub-tensor of `a` consisting of the appropriate
 
167
        number of its rightmost indices, and must be such that
 
168
       ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
 
169
       'square').
 
170
    b : array_like
 
171
        Right-hand tensor, which can be of any shape.
 
172
    axes : tuple of ints, optional
 
173
        Axes in `a` to reorder to the right, before inversion.
145
174
        If None (default), no reordering is done.
146
175
 
147
176
    Returns
148
177
    -------
149
 
    x : array, shape Q
 
178
    x : ndarray, shape Q
 
179
 
 
180
    Raises
 
181
    ------
 
182
    LinAlgError
 
183
        If `a` is singular or not 'square' (in the above sense).
 
184
 
 
185
    See Also
 
186
    --------
 
187
    tensordot, tensorinv
150
188
 
151
189
    Examples
152
190
    --------
153
191
    >>> a = np.eye(2*3*4)
154
 
    >>> a.shape = (2*3,4,  2,3,4)
155
 
    >>> b = np.random.randn(2*3,4)
 
192
    >>> a.shape = (2*3, 4, 2, 3, 4)
 
193
    >>> b = np.random.randn(2*3, 4)
156
194
    >>> x = np.linalg.tensorsolve(a, b)
157
195
    >>> x.shape
158
196
    (2, 3, 4)
184
222
 
185
223
def solve(a, b):
186
224
    """
187
 
    Solve the equation ``a x = b`` for ``x``.
 
225
    Solve a linear matrix equation, or system of linear scalar equations.
 
226
 
 
227
    Computes the "exact" solution, `x`, of the well-determined, i.e., full
 
228
    rank, linear matrix equation `ax = b`.
188
229
 
189
230
    Parameters
190
231
    ----------
191
232
    a : array_like, shape (M, M)
192
 
        Input equation coefficients.
193
 
    b : array_like, shape (M,)
194
 
        Equation target values.
 
233
        Coefficient matrix.
 
234
    b : array_like, shape (M,) or (M, N)
 
235
        Ordinate or "dependent variable" values.
195
236
 
196
237
    Returns
197
238
    -------
198
 
    x : array, shape (M,)
 
239
    x : ndarray, shape (M,) or (M, N) depending on b
 
240
        Solution to the system a x = b
199
241
 
200
242
    Raises
201
243
    ------
204
246
 
205
247
    Notes
206
248
    -----
207
 
 
208
 
    ``linalg.solve`` is a wrapper to the LAPACK http://www.netlib.org/lapack
209
 
    routines `dgesv`_ and `zgesv`_.  The solution to the system of linear
210
 
    equations is computed using an LU decomposition with partial pivoting and
 
249
    `solve` is a wrapper for the LAPACK routines `dgesv`_ and
 
250
    `zgesv`_, the former being used if `a` is real-valued, the latter if
 
251
    it is complex-valued.  The solution to the system of linear equations
 
252
    is computed using an LU decomposition [1]_ with partial pivoting and
211
253
    row interchanges.
212
254
 
213
255
    .. _dgesv: http://www.netlib.org/lapack/double/dgesv.f
214
256
 
215
257
    .. _zgesv: http://www.netlib.org/lapack/complex16/zgesv.f
216
258
 
 
259
    `a` must be square and of full-rank, i.e., all rows (or, equivalently,
 
260
    columns) must be linearly independent; if either is not true, use
 
261
    `lstsq` for the least-squares best "solution" of the
 
262
    system/equation.
 
263
 
 
264
    References
 
265
    ----------
 
266
    .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
 
267
           FL, Academic Press, Inc., 1980, pg. 22.
 
268
 
217
269
    Examples
218
270
    --------
219
271
    Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``:
260
312
 
261
313
def tensorinv(a, ind=2):
262
314
    """
263
 
    Find the 'inverse' of a N-d array
264
 
 
265
 
    The result is an inverse corresponding to the operation
266
 
    tensordot(a, b, ind), ie.,
267
 
 
268
 
        x == tensordot(tensordot(tensorinv(a), a, ind), x, ind)
269
 
          == tensordot(tensordot(a, tensorinv(a), ind), x, ind)
270
 
 
271
 
    for all x (up to floating-point accuracy).
 
315
    Compute the 'inverse' of an N-dimensional array.
 
316
 
 
317
    The result is an inverse for `a` relative to the tensordot operation
 
318
    ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
 
319
    ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
 
320
    tensordot operation.
272
321
 
273
322
    Parameters
274
323
    ----------
275
324
    a : array_like
276
 
        Tensor to 'invert'. Its shape must 'square', ie.,
277
 
        prod(a.shape[:ind]) == prod(a.shape[ind:])
278
 
    ind : integer > 0
279
 
        How many of the first indices are involved in the inverse sum.
 
325
        Tensor to 'invert'. Its shape must be 'square', i. e.,
 
326
        ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
 
327
    ind : int, optional
 
328
        Number of first indices that are involved in the inverse sum.
 
329
        Must be a positive integer, default is 2.
280
330
 
281
331
    Returns
282
332
    -------
283
 
    b : array, shape a.shape[:ind]+a.shape[ind:]
284
 
 
285
 
    Raises LinAlgError if a is singular or not square
 
333
    b : ndarray
 
334
        `a`'s tensordot inverse, shape ``a.shape[:ind] + a.shape[ind:]``.
 
335
 
 
336
    Raises
 
337
    ------
 
338
    LinAlgError
 
339
        If `a` is singular or not 'square' (in the above sense).
 
340
 
 
341
    See Also
 
342
    --------
 
343
    tensordot, tensorsolve
286
344
 
287
345
    Examples
288
346
    --------
289
347
    >>> a = np.eye(4*6)
290
 
    >>> a.shape = (4,6,8,3)
 
348
    >>> a.shape = (4, 6, 8, 3)
291
349
    >>> ainv = np.linalg.tensorinv(a, ind=2)
292
350
    >>> ainv.shape
293
351
    (8, 3, 4, 6)
294
 
    >>> b = np.random.randn(4,6)
 
352
    >>> b = np.random.randn(4, 6)
295
353
    >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
296
354
    True
297
355
 
298
356
    >>> a = np.eye(4*6)
299
 
    >>> a.shape = (24,8,3)
 
357
    >>> a.shape = (24, 8, 3)
300
358
    >>> ainv = np.linalg.tensorinv(a, ind=1)
301
359
    >>> ainv.shape
302
360
    (8, 3, 24)
323
381
 
324
382
def inv(a):
325
383
    """
326
 
    Compute the inverse of a matrix.
 
384
    Compute the (multiplicative) inverse of a matrix.
 
385
 
 
386
    Given a square matrix `a`, return the matrix `ainv` satisfying
 
387
    ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
327
388
 
328
389
    Parameters
329
390
    ----------
330
391
    a : array_like, shape (M, M)
331
 
        Matrix to be inverted
 
392
        Matrix to be inverted.
332
393
 
333
394
    Returns
334
395
    -------
335
 
    ainv : ndarray, shape (M, M)
336
 
        Inverse of the matrix `a`
 
396
    ainv : ndarray or matrix, shape (M, M)
 
397
        (Multiplicative) inverse of the matrix `a`.
337
398
 
338
399
    Raises
339
400
    ------
342
403
 
343
404
    Examples
344
405
    --------
 
406
    >>> from numpy import linalg as LA
345
407
    >>> a = np.array([[1., 2.], [3., 4.]])
346
 
    >>> np.linalg.inv(a)
347
 
    array([[-2. ,  1. ],
348
 
           [ 1.5, -0.5]])
349
 
    >>> np.dot(a, np.linalg.inv(a))
350
 
    array([[ 1.,  0.],
351
 
           [ 0.,  1.]])
 
408
    >>> ainv = LA.inv(a)
 
409
    >>> np.allclose(np.dot(a, ainv), np.eye(2))
 
410
    True
 
411
    >>> np.allclose(np.dot(ainv, a), np.eye(2))
 
412
    True
 
413
 
 
414
    If a is a matrix object, then the return value is a matrix as well:
 
415
 
 
416
    >>> ainv = LA.inv(np.matrix(a))
 
417
    >>> ainv
 
418
    matrix([[-2. ,  1. ],
 
419
            [ 1.5, -0.5]])
352
420
 
353
421
    """
354
422
    a, wrap = _makearray(a)
361
429
    """
362
430
    Cholesky decomposition.
363
431
 
364
 
    Return the Cholesky decomposition, :math:`A = L L^*` of a Hermitian
365
 
    positive-definite matrix :math:`A`.
 
432
    Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
 
433
    where `L` is lower-triangular and .H is the conjugate transpose operator
 
434
    (which is the ordinary transpose if `a` is real-valued).  `a` must be
 
435
    Hermitian (symmetric if real-valued) and positive-definite.  Only `L` is
 
436
    actually returned.
366
437
 
367
438
    Parameters
368
439
    ----------
369
440
    a : array_like, shape (M, M)
370
 
        Hermitian (symmetric, if it is real) and positive definite
 
441
        Hermitian (symmetric if all elements are real), positive-definite
371
442
        input matrix.
372
443
 
373
444
    Returns
374
445
    -------
375
 
    L : array_like, shape (M, M)
376
 
        Lower-triangular Cholesky factor of A.
 
446
    L : ndarray, or matrix object if `a` is, shape (M, M)
 
447
        Lower-triangular Cholesky factor of a.
377
448
 
378
449
    Raises
379
450
    ------
380
451
    LinAlgError
381
 
       If the decomposition fails.
 
452
       If the decomposition fails, for example, if `a` is not
 
453
       positive-definite.
382
454
 
383
455
    Notes
384
456
    -----
385
457
    The Cholesky decomposition is often used as a fast way of solving
386
458
 
387
 
    .. math:: A \\mathbf{x} = \\mathbf{b}.
 
459
    .. math:: A \\mathbf{x} = \\mathbf{b}
 
460
 
 
461
    (when `A` is both Hermitian/symmetric and positive-definite).
388
462
 
389
463
    First, we solve for :math:`\\mathbf{y}` in
390
464
 
392
466
 
393
467
    and then for :math:`\\mathbf{x}` in
394
468
 
395
 
    .. math:: L^* \\mathbf{x} = \\mathbf{y}.
 
469
    .. math:: L.H \\mathbf{x} = \\mathbf{y}.
396
470
 
397
471
    Examples
398
472
    --------
399
473
    >>> A = np.array([[1,-2j],[2j,5]])
 
474
    >>> A
 
475
    array([[ 1.+0.j,  0.-2.j],
 
476
           [ 0.+2.j,  5.+0.j]])
400
477
    >>> L = np.linalg.cholesky(A)
401
478
    >>> L
402
479
    array([[ 1.+0.j,  0.+0.j],
403
480
           [ 0.+2.j,  1.+0.j]])
404
 
    >>> np.dot(L, L.T.conj())
 
481
    >>> np.dot(L, L.T.conj()) # verify that L * L.H = A
405
482
    array([[ 1.+0.j,  0.-2.j],
406
483
           [ 0.+2.j,  5.+0.j]])
 
484
    >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
 
485
    >>> np.linalg.cholesky(A) # an ndarray object is returned
 
486
    array([[ 1.+0.j,  0.+0.j],
 
487
           [ 0.+2.j,  1.+0.j]])
 
488
    >>> # But a matrix object is returned if A is a matrix object
 
489
    >>> LA.cholesky(np.matrix(A))
 
490
    matrix([[ 1.+0.j,  0.+0.j],
 
491
            [ 0.+2.j,  1.+0.j]])
407
492
 
408
493
    """
409
494
    a, wrap = _makearray(a)
430
515
 
431
516
def qr(a, mode='full'):
432
517
    """
433
 
    Compute QR decomposition of a matrix.
 
518
    Compute the qr factorization of a matrix.
434
519
 
435
 
    Calculate the decomposition :math:`A = Q R` where Q is orthonormal
436
 
    and R upper triangular.
 
520
    Factor the matrix `a` as `qr`, where `q` is orthonormal
 
521
    (:math:`dot( q_{:,i}, q_{:,j}) = \\delta_{ij}`, the Kronecker delta) and
 
522
    `r` is upper-triangular.
437
523
 
438
524
    Parameters
439
525
    ----------
440
526
    a : array_like, shape (M, N)
441
 
        Matrix to be decomposed
 
527
        Matrix to be factored.
442
528
    mode : {'full', 'r', 'economic'}
443
 
        Determines what information is to be returned. 'full' is the default.
444
 
        Economic mode is slightly faster if only R is needed.
 
529
        Specifies the information to be returned. 'full' is the default.
 
530
        mode='r' returns a "true" `r`, while 'economic' returns a "polluted"
 
531
        `r` (albeit slightly faster; see Returns below).
445
532
 
446
533
    Returns
447
534
    -------
448
 
    mode = 'full'
449
 
    Q : double or complex array, shape (M, K)
450
 
    R : double or complex array, shape (K, N)
451
 
        Size K = min(M, N)
452
 
 
453
 
    mode = 'r'
454
 
    R : double or complex array, shape (K, N)
455
 
 
456
 
    mode = 'economic'
457
 
    A2 : double or complex array, shape (M, N)
458
 
        The diagonal and the upper triangle of A2 contains R,
459
 
        while the rest of the matrix is undefined.
460
 
 
461
 
    If a is a matrix, so are all the return values.
462
 
 
463
 
    Raises LinAlgError if decomposition fails
 
535
    * If mode = 'full':
 
536
 
 
537
        * q : ndarray of float or complex, shape (M, K)
 
538
        * r : ndarray of float or complex, shape (K, N)
 
539
 
 
540
      Size K = min(M, N)
 
541
 
 
542
    * If mode = 'r':
 
543
 
 
544
      * r : ndarray of float or complex, shape (K, N)
 
545
 
 
546
    * If mode = 'economic':
 
547
 
 
548
      * a2 : ndarray of float or complex, shape (M, N)
 
549
 
 
550
      The diagonal and the upper triangle of a2 contains r,
 
551
      while the rest of the matrix is undefined.
 
552
 
 
553
    Raises
 
554
    ------
 
555
    LinAlgError
 
556
        If factoring fails.
464
557
 
465
558
    Notes
466
559
    -----
467
560
    This is an interface to the LAPACK routines dgeqrf, zgeqrf,
468
561
    dorgqr, and zungqr.
469
562
 
 
563
    For more information on the qr factorization, see for example:
 
564
    http://en.wikipedia.org/wiki/QR_factorization
 
565
 
 
566
    Subclasses of `ndarray` are preserved, so if `a` is of type `matrix`,
 
567
    all the return values will be matrices too.
 
568
 
470
569
    Examples
471
570
    --------
472
571
    >>> a = np.random.randn(9, 6)
473
572
    >>> q, r = np.linalg.qr(a)
474
 
    >>> np.allclose(a, np.dot(q, r))
 
573
    >>> np.allclose(a, np.dot(q, r))  # a does equal qr
475
574
    True
476
575
    >>> r2 = np.linalg.qr(a, mode='r')
477
576
    >>> r3 = np.linalg.qr(a, mode='economic')
478
 
    >>> np.allclose(r, r2)
 
577
    >>> np.allclose(r, r2)  # mode='r' returns the same r as mode='full'
479
578
    True
 
579
    >>> # But only triu parts are guaranteed equal when mode='economic'
480
580
    >>> np.allclose(r, np.triu(r3[:6,:6], k=0))
481
581
    True
482
582
 
 
583
    Example illustrating a common use of `qr`: solving of least squares
 
584
    problems
 
585
 
 
586
    What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
 
587
    the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
 
588
    and you'll see that it should be y0 = 0, m = 1.)  The answer is provided
 
589
    by solving the over-determined matrix equation ``Ax = b``, where::
 
590
 
 
591
      A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
 
592
      x = array([[y0], [m]])
 
593
      b = array([[1], [0], [2], [1]])
 
594
 
 
595
    If A = qr such that q is orthonormal (which is always possible via
 
596
    Gram-Schmidt), then ``x = inv(r) * (q.T) * b``.  (In numpy practice,
 
597
    however, we simply use `lstsq`.)
 
598
 
 
599
    >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
 
600
    >>> A
 
601
    array([[0, 1],
 
602
           [1, 1],
 
603
           [1, 1],
 
604
           [2, 1]])
 
605
    >>> b = np.array([1, 0, 2, 1])
 
606
    >>> q, r = LA.qr(A)
 
607
    >>> p = np.dot(q.T, b)
 
608
    >>> np.dot(LA.inv(r), p)
 
609
    array([  1.1e-16,   1.0e+00])
 
610
 
483
611
    """
484
612
    a, wrap = _makearray(a)
485
613
    _assertRank2(a)
560
688
    """
561
689
    Compute the eigenvalues of a general matrix.
562
690
 
 
691
    Main difference between `eigvals` and `eig`: the eigenvectors aren't
 
692
    returned.
 
693
 
563
694
    Parameters
564
695
    ----------
565
696
    a : array_like, shape (M, M)
566
 
        A complex or real matrix whose eigenvalues and eigenvectors
567
 
        will be computed.
 
697
        A complex- or real-valued matrix whose eigenvalues will be computed.
568
698
 
569
699
    Returns
570
700
    -------
581
711
    See Also
582
712
    --------
583
713
    eig : eigenvalues and right eigenvectors of general arrays
584
 
    eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
585
 
    eigh : eigenvalues and eigenvectors of symmetric/Hermitean arrays.
 
714
    eigvalsh : eigenvalues of symmetric or Hermitian arrays.
 
715
    eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.
586
716
 
587
717
    Notes
588
718
    -----
589
719
    This is a simple interface to the LAPACK routines dgeev and zgeev
590
 
    that sets the flags to return only the eigenvalues of general real
591
 
    and complex arrays respectively.
592
 
 
593
 
    The number w is an eigenvalue of a if there exists a vector v
594
 
    satisfying the equation dot(a,v) = w*v. Alternately, if w is a root of
595
 
    the characteristic equation det(a - w[i]*I) = 0, where det is the
596
 
    determinant and I is the identity matrix.
 
720
    that sets those routines' flags to return only the eigenvalues of
 
721
    general real and complex arrays, respectively.
 
722
 
 
723
    Examples
 
724
    --------
 
725
    Illustration, using the fact that the eigenvalues of a diagonal matrix
 
726
    are its diagonal elements, that multiplying a matrix on the left
 
727
    by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
 
728
    of `Q`), preserves the eigenvalues of the "middle" matrix.  In other words,
 
729
    if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
 
730
    ``A``:
 
731
 
 
732
    >>> from numpy import linalg as LA
 
733
    >>> x = np.random.random()
 
734
    >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
 
735
    >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
 
736
    (1.0, 1.0, 0.0)
 
737
 
 
738
    Now multiply a diagonal matrix by Q on one side and by Q.T on the other:
 
739
 
 
740
    >>> D = np.diag((-1,1))
 
741
    >>> LA.eigvals(D)
 
742
    array([-1.,  1.])
 
743
    >>> A = np.dot(Q, D)
 
744
    >>> A = np.dot(A, Q.T)
 
745
    >>> LA.eigvals(A)
 
746
    array([ 1., -1.])
597
747
 
598
748
    """
599
749
    a, wrap = _makearray(a)
642
792
 
643
793
def eigvalsh(a, UPLO='L'):
644
794
    """
645
 
    Compute the eigenvalues of a Hermitean or real symmetric matrix.
 
795
    Compute the eigenvalues of a Hermitian or real symmetric matrix.
 
796
 
 
797
    Main difference from eigh: the eigenvectors are not computed.
646
798
 
647
799
    Parameters
648
800
    ----------
649
801
    a : array_like, shape (M, M)
650
 
        A complex or real matrix whose eigenvalues and eigenvectors
651
 
        will be computed.
 
802
        A complex- or real-valued matrix whose eigenvalues are to be
 
803
        computed.
652
804
    UPLO : {'L', 'U'}, optional
653
 
        Specifies whether the calculation is done with data from the
654
 
        lower triangular part of `a` ('L', default) or the upper triangular
655
 
        part ('U').
 
805
        Specifies whether the calculation is done with the lower triangular
 
806
        part of `a` ('L', default) or the upper triangular part ('U').
656
807
 
657
808
    Returns
658
809
    -------
659
810
    w : ndarray, shape (M,)
660
 
        The eigenvalues, each repeated according to its multiplicity.
661
 
        They are not necessarily ordered.
 
811
        The eigenvalues, not necessarily ordered, each repeated according to
 
812
        its multiplicity.
662
813
 
663
814
    Raises
664
815
    ------
667
818
 
668
819
    See Also
669
820
    --------
670
 
    eigh : eigenvalues and eigenvectors of symmetric/Hermitean arrays.
 
821
    eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.
671
822
    eigvals : eigenvalues of general real or complex arrays.
672
 
    eig : eigenvalues and eigenvectors of general real or complex arrays.
 
823
    eig : eigenvalues and right eigenvectors of general real or complex
 
824
          arrays.
673
825
 
674
826
    Notes
675
827
    -----
676
 
    This is a simple interface to the LAPACK routines dsyevd and
677
 
    zheevd that sets the flags to return only the eigenvalues of real
678
 
    symmetric and complex Hermetian arrays respectively.
 
828
    This is a simple interface to the LAPACK routines dsyevd and zheevd
 
829
    that sets those routines' flags to return only the eigenvalues of
 
830
    real symmetric and complex Hermitian arrays, respectively.
679
831
 
680
 
    The number w is an eigenvalue of a if there exists a vector v
681
 
    satisfying the equation dot(a,v) = w*v. Alternately, if w is a root of
682
 
    the characteristic equation det(a - w[i]*I) = 0, where det is the
683
 
    determinant and I is the identity matrix.
 
832
    Examples
 
833
    --------
 
834
    >>> from numpy import linalg as LA
 
835
    >>> a = np.array([[1, -2j], [2j, 5]])
 
836
    >>> LA.eigvalsh(a)
 
837
    array([ 0.17157288+0.j,  5.82842712+0.j])
684
838
 
685
839
    """
686
840
    a, wrap = _makearray(a)
733
887
 
734
888
def eig(a):
735
889
    """
736
 
    Compute eigenvalues and right eigenvectors of an array.
 
890
    Compute the eigenvalues and right eigenvectors of a square array.
737
891
 
738
892
    Parameters
739
893
    ----------
740
894
    a : array_like, shape (M, M)
741
 
        A complex or real 2-D array.
 
895
        A square array of real or complex elements.
742
896
 
743
897
    Returns
744
898
    -------
745
899
    w : ndarray, shape (M,)
746
900
        The eigenvalues, each repeated according to its multiplicity.
747
901
        The eigenvalues are not necessarily ordered, nor are they
748
 
        necessarily real for real matrices.
 
902
        necessarily real for real arrays (though for real arrays
 
903
        complex-valued eigenvalues should occur in conjugate pairs).
 
904
 
749
905
    v : ndarray, shape (M, M)
750
 
        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
751
 
        the column ``v[:,i]``.
 
906
        The normalized (unit "length") eigenvectors, such that the
 
907
        column ``v[:,i]`` is the eigenvector corresponding to the
 
908
        eigenvalue ``w[i]``.
752
909
 
753
910
    Raises
754
911
    ------
757
914
 
758
915
    See Also
759
916
    --------
760
 
    eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
761
 
    eig : eigenvalues and right eigenvectors for non-symmetric arrays
762
 
    eigvals : eigenvalues of non-symmetric array.
 
917
    eigvalsh : eigenvalues of a symmetric or Hermitian (conjugate symmetric)
 
918
       array.
 
919
 
 
920
    eigvals : eigenvalues of a non-symmetric array.
763
921
 
764
922
    Notes
765
923
    -----
766
924
    This is a simple interface to the LAPACK routines dgeev and zgeev
767
 
    that compute the eigenvalues and eigenvectors of general real and
768
 
    complex arrays respectively.
 
925
    which compute the eigenvalues and eigenvectors of, respectively,
 
926
    general real- and complex-valued square arrays.
769
927
 
770
 
    The number `w` is an eigenvalue of a if there exists a vector `v`
771
 
    satisfying the equation ``dot(a,v) = w*v``. Alternately, if `w` is
772
 
    a root of the characteristic equation ``det(a - w[i]*I) = 0``, where
773
 
    `det` is the determinant and `I` is the identity matrix. The arrays
774
 
    `a`, `w`, and `v` satisfy the equation ``dot(a,v[i]) = w[i]*v[:,i]``.
 
928
    The number `w` is an eigenvalue of `a` if there exists a vector
 
929
    `v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
 
930
    `v` satisfy the equations ``dot(a[i,:], v[i]) = w[i] * v[:,i]``
 
931
    for :math:`i \\in \\{0,...,M-1\\}`.
775
932
 
776
933
    The array `v` of eigenvectors may not be of maximum rank, that is, some
777
 
    of the columns may be dependent, although roundoff error may
 
934
    of the columns may be linearly dependent, although round-off error may
778
935
    obscure that fact. If the eigenvalues are all different, then theoretically
779
 
    the eigenvectors are independent. Likewise, the matrix of eigenvectors
780
 
    is unitary if the matrix `a` is normal, i.e., if
781
 
    ``dot(a, a.H) = dot(a.H, a)``.
782
 
 
783
 
    The left and right eigenvectors are not necessarily the (Hermitian)
784
 
    transposes of each other.
 
936
    the eigenvectors are linearly independent. Likewise, the (complex-valued)
 
937
    matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e.,
 
938
    if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate
 
939
    transpose of `a`.
 
940
 
 
941
    Finally, it is emphasized that `v` consists of the *right* (as in
 
942
    right-hand side) eigenvectors of `a`.  A vector `y` satisfying
 
943
    ``dot(y.T, a) = z * y.T`` for some number `z` is called a *left*
 
944
    eigenvector of `a`, and, in general, the left and right eigenvectors
 
945
    of a matrix are not necessarily the (perhaps conjugate) transposes
 
946
    of each other.
 
947
 
 
948
    References
 
949
    ----------
 
950
    G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
 
951
    Academic Press, Inc., 1980, Various pp.
 
952
 
 
953
    Examples
 
954
    --------
 
955
    >>> from numpy import linalg as LA
 
956
 
 
957
    (Almost) trivial example with real e-values and e-vectors.
 
958
 
 
959
    >>> w, v = LA.eig(np.diag((1, 2, 3)))
 
960
    >>> w; v
 
961
    array([ 1.,  2.,  3.])
 
962
    array([[ 1.,  0.,  0.],
 
963
           [ 0.,  1.,  0.],
 
964
           [ 0.,  0.,  1.]])
 
965
 
 
966
    Real matrix possessing complex e-values and e-vectors; note that the
 
967
    e-values are complex conjugates of each other.
 
968
 
 
969
    >>> w, v = LA.eig(np.array([[1, -1], [1, 1]]))
 
970
    >>> w; v
 
971
    array([ 1. + 1.j,  1. - 1.j])
 
972
    array([[ 0.70710678+0.j        ,  0.70710678+0.j        ],
 
973
           [ 0.00000000-0.70710678j,  0.00000000+0.70710678j]])
 
974
 
 
975
    Complex-valued matrix with real e-values (but complex-valued e-vectors);
 
976
    note that a.conj().T = a, i.e., a is Hermitian.
 
977
 
 
978
    >>> a = np.array([[1, 1j], [-1j, 1]])
 
979
    >>> w, v = LA.eig(a)
 
980
    >>> w; v
 
981
    array([  2.00000000e+00+0.j,   5.98651912e-36+0.j]) # i.e., {2, 0}
 
982
    array([[ 0.00000000+0.70710678j,  0.70710678+0.j        ],
 
983
           [ 0.70710678+0.j        ,  0.00000000+0.70710678j]])
 
984
 
 
985
    Be careful about round-off error!
 
986
 
 
987
    >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
 
988
    >>> # Theor. e-values are 1 +/- 1e-9
 
989
    >>> w, v = LA.eig(a)
 
990
    >>> w; v
 
991
    array([ 1.,  1.])
 
992
    array([[ 1.,  0.],
 
993
           [ 0.,  1.]])
785
994
 
786
995
    """
787
996
    a, wrap = _makearray(a)
840
1049
 
841
1050
def eigh(a, UPLO='L'):
842
1051
    """
843
 
    Eigenvalues and eigenvectors of a Hermitian or real symmetric matrix.
 
1052
    Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix.
 
1053
 
 
1054
    Returns two objects, a 1-D array containing the eigenvalues of `a`, and
 
1055
    a 2-D square array or matrix (depending on the input type) of the
 
1056
    corresponding eigenvectors (in columns).
844
1057
 
845
1058
    Parameters
846
1059
    ----------
847
1060
    a : array_like, shape (M, M)
848
 
        A complex Hermitian or symmetric real matrix.
 
1061
        A complex Hermitian or real symmetric matrix.
849
1062
    UPLO : {'L', 'U'}, optional
850
 
        Specifies whether the calculation is done with data from the
851
 
        lower triangular part of `a` ('L', default) or the upper triangular
852
 
        part ('U').
 
1063
        Specifies whether the calculation is done with the lower triangular
 
1064
        part of `a` ('L', default) or the upper triangular part ('U').
853
1065
 
854
1066
    Returns
855
1067
    -------
856
1068
    w : ndarray, shape (M,)
857
 
        The eigenvalues. The eigenvalues are not necessarily ordered.
858
 
    v : ndarray, shape (M, M)
859
 
        The normalized eigenvector corresponding to the eigenvalue w[i] is
860
 
        the column v[:,i].
 
1069
        The eigenvalues, not necessarily ordered.
 
1070
    v : ndarray, or matrix object if `a` is, shape (M, M)
 
1071
        The column ``v[:, i]`` is the normalized eigenvector corresponding
 
1072
        to the eigenvalue ``w[i]``.
861
1073
 
862
1074
    Raises
863
1075
    ------
866
1078
 
867
1079
    See Also
868
1080
    --------
869
 
    eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
870
 
    eig : eigenvalues and right eigenvectors for non-symmetric arrays
871
 
    eigvals : eigenvalues of non-symmetric array.
 
1081
    eigvalsh : eigenvalues of symmetric or Hermitian arrays.
 
1082
    eig : eigenvalues and right eigenvectors for non-symmetric arrays.
 
1083
    eigvals : eigenvalues of non-symmetric arrays.
872
1084
 
873
1085
    Notes
874
1086
    -----
875
 
    A simple interface to the LAPACK routines dsyevd and zheevd that compute
876
 
    the eigenvalues and eigenvectors of real symmetric and complex Hermitian
877
 
    arrays respectively.
878
 
 
879
 
    The number w is an eigenvalue of a if there exists a vector v
880
 
    satisfying the equation dot(a,v) = w*v. Alternately, if w is a root of
881
 
    the characteristic equation det(a - w[i]*I) = 0, where det is the
882
 
    determinant and I is the identity matrix. The eigenvalues of real
883
 
    symmetric or complex Hermitean matrices are always real. The array v
884
 
    of eigenvectors is unitary and a, w, and v satisfy the equation
885
 
    dot(a,v[i]) = w[i]*v[:,i].
 
1087
    This is a simple interface to the LAPACK routines dsyevd and zheevd,
 
1088
    which compute the eigenvalues and eigenvectors of real symmetric and
 
1089
    complex Hermitian arrays, respectively.
 
1090
 
 
1091
    The eigenvalues of real symmetric or complex Hermitian matrices are
 
1092
    always real. [1]_ The array `v` of (column) eigenvectors is unitary
 
1093
    and `a`, `w`, and `v` satisfy the equations
 
1094
    ``dot(a, v[:, i]) = w[i] * v[:, i]``.
 
1095
 
 
1096
    References
 
1097
    ----------
 
1098
    .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
 
1099
           FL, Academic Press, Inc., 1980, pg. 222.
 
1100
 
 
1101
    Examples
 
1102
    --------
 
1103
    >>> from numpy import linalg as LA
 
1104
    >>> a = np.array([[1, -2j], [2j, 5]])
 
1105
    >>> a
 
1106
    array([[ 1.+0.j,  0.-2.j],
 
1107
           [ 0.+2.j,  5.+0.j]])
 
1108
    >>> w, v = LA.eigh(a)
 
1109
    >>> w; v
 
1110
    array([ 0.17157288,  5.82842712])
 
1111
    array([[-0.92387953+0.j        , -0.38268343+0.j        ],
 
1112
           [ 0.00000000+0.38268343j,  0.00000000-0.92387953j]])
 
1113
 
 
1114
    >>> np.dot(a, v[:, 0]) - w[0] * v[:, 0] # verify 1st e-val/vec pair
 
1115
    array([2.77555756e-17 + 0.j, 0. + 1.38777878e-16j])
 
1116
    >>> np.dot(a, v[:, 1]) - w[1] * v[:, 1] # verify 2nd e-val/vec pair
 
1117
    array([ 0.+0.j,  0.+0.j])
 
1118
 
 
1119
    >>> A = np.matrix(a) # what happens if input is a matrix object
 
1120
    >>> A
 
1121
    matrix([[ 1.+0.j,  0.-2.j],
 
1122
            [ 0.+2.j,  5.+0.j]])
 
1123
    >>> w, v = LA.eigh(A)
 
1124
    >>> w; v
 
1125
    array([ 0.17157288,  5.82842712])
 
1126
    matrix([[-0.92387953+0.j        , -0.38268343+0.j        ],
 
1127
            [ 0.00000000+0.38268343j,  0.00000000-0.92387953j]])
886
1128
 
887
1129
    """
888
1130
    a, wrap = _makearray(a)
932
1174
    """
933
1175
    Singular Value Decomposition.
934
1176
 
935
 
    Factorizes the matrix `a` into two unitary matrices, ``U`` and ``Vh``,
936
 
    and a 1-dimensional array of singular values, ``s`` (real, non-negative),
937
 
    such that ``a == U S Vh``, where ``S`` is the diagonal
938
 
    matrix ``np.diag(s)``.
 
1177
    Factors the matrix `a` into ``u * np.diag(s) * v.H``, where `u` and `v`
 
1178
    are unitary (i.e., ``u.H = inv(u)`` and similarly for `v`), ``.H`` is the
 
1179
    conjugate transpose operator (which is the ordinary transpose for
 
1180
    real-valued matrices), and `s` is a 1-D array of `a`'s singular values.
939
1181
 
940
1182
    Parameters
941
1183
    ----------
942
 
    a : array_like, shape (M, N)
943
 
        Matrix to decompose
944
 
    full_matrices : boolean, optional
945
 
        If True (default), ``U`` and ``Vh`` are shaped
946
 
        ``(M,M)`` and ``(N,N)``.  Otherwise, the shapes are
947
 
        ``(M,K)`` and ``(K,N)``, where ``K = min(M,N)``.
948
 
    compute_uv : boolean
949
 
        Whether to compute ``U`` and ``Vh`` in addition to ``s``.
 
1184
    a : array_like
 
1185
        Matrix of shape ``(M, N)`` to decompose.
 
1186
    full_matrices : bool, optional
 
1187
        If True (default), ``u`` and ``v.H`` have the shapes
 
1188
        ``(M, M)`` and ``(N, N)``, respectively.  Otherwise, the shapes
 
1189
        are ``(M, K)`` and ``(K, N)``, resp., where ``K = min(M, N)``.
 
1190
    compute_uv : bool, optional
 
1191
        Whether or not to compute ``u`` and ``v.H`` in addition to ``s``.
950
1192
        True by default.
951
1193
 
952
1194
    Returns
953
1195
    -------
954
 
    U : ndarray, shape (M, M) or (M, K) depending on `full_matrices`
955
 
        Unitary matrix.
956
 
    s :  ndarray, shape (K,) where ``K = min(M, N)``
 
1196
    u : ndarray
 
1197
        Unitary matrix. The shape of `U` is ``(M, M)`` or ``(M, K)``
 
1198
        depending on value of `full_matrices`.
 
1199
    s : ndarray
957
1200
        The singular values, sorted so that ``s[i] >= s[i+1]``.
958
 
    Vh : ndarray, shape (N,N) or (K,N) depending on `full_matrices`
959
 
        Unitary matrix.
 
1201
        `S` is a 1-D array of length ``min(M, N)``
 
1202
    v.H : ndarray
 
1203
        Unitary matrix of shape ``(N, N)`` or ``(K, N)``, depending
 
1204
        on `full_matrices`.
960
1205
 
961
1206
    Raises
962
1207
    ------
965
1210
 
966
1211
    Notes
967
1212
    -----
968
 
    If `a` is a matrix (in contrast to an ndarray), then so are all
 
1213
    If `a` is a matrix object (as opposed to an `ndarray`), then so are all
969
1214
    the return values.
970
1215
 
971
1216
    Examples
1049
1294
    """
1050
1295
    Compute the condition number of a matrix.
1051
1296
 
1052
 
    The condition number of `x` is the norm of `x` times the norm
1053
 
    of the inverse of `x`.  The norm can be the usual L2
1054
 
    (root-of-sum-of-squares) norm or a number of other matrix norms.
 
1297
    This function is capable of returning the condition number using
 
1298
    one of seven different norms, depending on the value of `p` (see
 
1299
    Parameters below).
1055
1300
 
1056
1301
    Parameters
1057
1302
    ----------
1058
1303
    x : array_like, shape (M, N)
1059
1304
        The matrix whose condition number is sought.
1060
 
    p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}
 
1305
    p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
1061
1306
        Order of the norm:
1062
1307
 
1063
1308
        =====  ============================
1064
1309
        p      norm for matrices
1065
1310
        =====  ============================
1066
 
        None   2-norm, computed directly using the SVD
 
1311
        None   2-norm, computed directly using the ``SVD``
1067
1312
        'fro'  Frobenius norm
1068
1313
        inf    max(sum(abs(x), axis=1))
1069
1314
        -inf   min(sum(abs(x), axis=1))
1073
1318
        -2     smallest singular value
1074
1319
        =====  ============================
1075
1320
 
 
1321
        inf means the numpy.inf object, and the Frobenius norm is
 
1322
        the root-of-sum-of-squares norm.
 
1323
 
1076
1324
    Returns
1077
1325
    -------
1078
 
    c : float
 
1326
    c : {float, inf}
1079
1327
        The condition number of the matrix. May be infinite.
1080
1328
 
 
1329
    See Also
 
1330
    --------
 
1331
    numpy.linalg.linalg.norm
 
1332
 
 
1333
    Notes
 
1334
    -----
 
1335
    The condition number of `x` is defined as the norm of `x` times the
 
1336
    norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
 
1337
    (root-of-sum-of-squares) or one of a number of other matrix norms.
 
1338
 
 
1339
    References
 
1340
    ----------
 
1341
    .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
 
1342
           Academic Press, Inc., 1980, pg. 285.
 
1343
 
 
1344
    Examples
 
1345
    --------
 
1346
    >>> from numpy import linalg as LA
 
1347
    >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
 
1348
    >>> a
 
1349
    array([[ 1,  0, -1],
 
1350
           [ 0,  1,  0],
 
1351
           [ 1,  0,  1]])
 
1352
    >>> LA.cond(a)
 
1353
    1.4142135623730951
 
1354
    >>> LA.cond(a, 'fro')
 
1355
    3.1622776601683795
 
1356
    >>> LA.cond(a, np.inf)
 
1357
    2.0
 
1358
    >>> LA.cond(a, -np.inf)
 
1359
    1.0
 
1360
    >>> LA.cond(a, 1)
 
1361
    2.0
 
1362
    >>> LA.cond(a, -1)
 
1363
    1.0
 
1364
    >>> LA.cond(a, 2)
 
1365
    1.4142135623730951
 
1366
    >>> LA.cond(a, -2)
 
1367
    0.70710678118654746
 
1368
    >>> min(LA.svd(a, compute_uv=0))*min(LA.svd(LA.inv(a), compute_uv=0))
 
1369
    0.70710678118654746
 
1370
 
1081
1371
    """
1082
1372
    x = asarray(x) # in case we have a matrix
1083
1373
    if p is None:
1094
1384
 
1095
1385
    Calculate the generalized inverse of a matrix using its
1096
1386
    singular-value decomposition (SVD) and including all
1097
 
    `large` singular values.
 
1387
    *large* singular values.
1098
1388
 
1099
1389
    Parameters
1100
1390
    ----------
1101
 
    a : array_like (M, N)
 
1391
    a : array_like, shape (M, N)
1102
1392
      Matrix to be pseudo-inverted.
1103
1393
    rcond : float
1104
 
      Cutoff for `small` singular values.
1105
 
      Singular values smaller than rcond*largest_singular_value are
1106
 
      considered zero.
 
1394
      Cutoff for small singular values.
 
1395
      Singular values smaller (in modulus) than
 
1396
      `rcond` * largest_singular_value (again, in modulus)
 
1397
      are set to zero.
1107
1398
 
1108
1399
    Returns
1109
1400
    -------
1110
 
    B : ndarray (N, M)
1111
 
      The pseudo-inverse of `a`. If `a` is an np.matrix instance, then so
 
1401
    B : ndarray, shape (N, M)
 
1402
      The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
1112
1403
      is `B`.
1113
1404
 
1114
 
 
1115
1405
    Raises
1116
1406
    ------
1117
1407
    LinAlgError
1118
 
      In case SVD computation does not converge.
 
1408
      If the SVD computation does not converge.
 
1409
 
 
1410
    Notes
 
1411
    -----
 
1412
    The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
 
1413
    defined as: "the matrix that 'solves' [the least-squares problem]
 
1414
    :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
 
1415
    :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
 
1416
 
 
1417
    It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
 
1418
    value decomposition of A, then
 
1419
    :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
 
1420
    orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
 
1421
    of A's so-called singular values, (followed, typically, by
 
1422
    zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
 
1423
    consisting of the reciprocals of A's singular values
 
1424
    (again, followed by zeros). [1]_
 
1425
 
 
1426
    References
 
1427
    ----------
 
1428
    .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
 
1429
           FL, Academic Press, Inc., 1980, pp. 139-142.
1119
1430
 
1120
1431
    Examples
1121
1432
    --------
 
1433
    The following example checks that ``a * a+ * a == a`` and
 
1434
    ``a+ * a * a+ == a+``:
 
1435
 
1122
1436
    >>> a = np.random.randn(9, 6)
1123
1437
    >>> B = np.linalg.pinv(a)
1124
1438
    >>> np.allclose(a, np.dot(a, np.dot(B, a)))
1197
1511
 
1198
1512
def lstsq(a, b, rcond=-1):
1199
1513
    """
1200
 
    Return the least-squares solution to an equation.
 
1514
    Return the least-squares solution to a linear matrix equation.
1201
1515
 
1202
1516
    Solves the equation `a x = b` by computing a vector `x` that minimizes
1203
 
    the norm `|| b - a x ||`.
 
1517
    the norm `|| b - a x ||`.  The equation may be under-, well-, or over-
 
1518
    determined (i.e., the number of linearly independent rows of `a` can be
 
1519
    less than, equal to, or greater than its number of linearly independent
 
1520
    columns).  If `a` is square and of full rank, then `x` (but for round-off
 
1521
    error) is the "exact" solution of the equation.
1204
1522
 
1205
1523
    Parameters
1206
1524
    ----------
1207
1525
    a : array_like, shape (M, N)
1208
 
        Input equation coefficients.
 
1526
        "Coefficient" matrix.
1209
1527
    b : array_like, shape (M,) or (M, K)
1210
 
        Equation target values.  If `b` is two-dimensional, the least
1211
 
        squares solution is calculated for each of the `K` target sets.
 
1528
        Ordinate or "dependent variable" values. If `b` is two-dimensional,
 
1529
        the least-squares solution is calculated for each of the `K` columns
 
1530
        of `b`.
1212
1531
    rcond : float, optional
1213
 
        Cutoff for ``small`` singular values of `a`.
1214
 
        Singular values smaller than `rcond` times the largest singular
1215
 
        value are  considered zero.
 
1532
        Cut-off ratio for small singular values of `a`.
 
1533
        Singular values are set to zero if they are smaller than `rcond`
 
1534
        times the largest singular value of `a`.
1216
1535
 
1217
1536
    Returns
1218
1537
    -------
1219
 
    x : ndarray, shape(N,) or (N, K)
1220
 
         Least squares solution.  The shape of `x` depends on the shape of
1221
 
         `b`.
1222
 
    residues : ndarray, shape(), (1,), or (K,)
1223
 
        Sums of residues; squared Euclidian norm for each column in
1224
 
        `b - a x`.
 
1538
    x : ndarray, shape (N,) or (N, K)
 
1539
        Least-squares solution.  The shape of `x` depends on the shape of
 
1540
        `b`.
 
1541
    residues : ndarray, shape (), (1,), or (K,)
 
1542
        Sums of residues; squared Euclidean norm for each column in
 
1543
        ``b - a*x``.
1225
1544
        If the rank of `a` is < N or > M, this is an empty array.
1226
1545
        If `b` is 1-dimensional, this is a (1,) shape array.
1227
1546
        Otherwise the shape is (K,).
1228
 
    rank : integer
 
1547
    rank : int
1229
1548
        Rank of matrix `a`.
1230
 
    s : ndarray, shape(min(M,N),)
 
1549
    s : ndarray, shape (min(M,N),)
1231
1550
        Singular values of `a`.
1232
1551
 
1233
1552
    Raises
1237
1556
 
1238
1557
    Notes
1239
1558
    -----
1240
 
    If `b` is a matrix, then all array results returned as
1241
 
    matrices.
 
1559
    If `b` is a matrix, then all array results are returned as matrices.
1242
1560
 
1243
1561
    Examples
1244
1562
    --------
1248
1566
    >>> y = np.array([-1, 0.2, 0.9, 2.1])
1249
1567
 
1250
1568
    By examining the coefficients, we see that the line should have a
1251
 
    gradient of roughly 1 and cuts the y-axis at more-or-less -1.
 
1569
    gradient of roughly 1 and cut the y-axis at, more or less, -1.
1252
1570
 
1253
1571
    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
1254
1572
    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:
1341
1659
    """
1342
1660
    Matrix or vector norm.
1343
1661
 
 
1662
    This function is able to return one of seven different matrix norms,
 
1663
    or one of an infinite number of vector norms (described below), depending
 
1664
    on the value of the ``ord`` parameter.
 
1665
 
1344
1666
    Parameters
1345
1667
    ----------
1346
1668
    x : array_like, shape (M,) or (M, N)
1347
1669
        Input array.
1348
 
    ord : {2, int, inf, -inf, 'fro'}
1349
 
        Order of the norm (see table under ``Notes``).
 
1670
    ord : {non-zero int, inf, -inf, 'fro'}, optional
 
1671
        Order of the norm (see table under ``Notes``). inf means numpy's
 
1672
        `inf` object.
1350
1673
 
1351
1674
    Returns
1352
1675
    -------
1353
1676
    n : float
1354
 
        Norm of the matrix or vector
 
1677
        Norm of the matrix or vector.
1355
1678
 
1356
1679
    Notes
1357
1680
    -----
1358
 
    For values ord < 0, the result is, strictly speaking, not a
1359
 
    mathematical 'norm', but it may still be useful for numerical
 
1681
    For values of ``ord <= 0``, the result is, strictly speaking, not a
 
1682
    mathematical 'norm', but it may still be useful for various numerical
1360
1683
    purposes.
1361
1684
 
1362
1685
    The following norms can be calculated:
1368
1691
    'fro'  Frobenius norm                --
1369
1692
    inf    max(sum(abs(x), axis=1))      max(abs(x))
1370
1693
    -inf   min(sum(abs(x), axis=1))      min(abs(x))
 
1694
    0      --                            sum(x != 0)
1371
1695
    1      max(sum(abs(x), axis=0))      as below
1372
1696
    -1     min(sum(abs(x), axis=0))      as below
1373
1697
    2      2-norm (largest sing. value)  as below
1375
1699
    other  --                            sum(abs(x)**ord)**(1./ord)
1376
1700
    =====  ============================  ==========================
1377
1701
 
 
1702
    The Frobenius norm is given by [1]_:
 
1703
 
 
1704
        :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
 
1705
 
 
1706
    References
 
1707
    ----------
 
1708
    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
 
1709
           Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
 
1710
 
 
1711
    Examples
 
1712
    --------
 
1713
    >>> from numpy import linalg as LA
 
1714
    >>> a = np.arange(9) - 4
 
1715
    >>> a
 
1716
    array([-4, -3, -2, -1,  0,  1,  2,  3,  4])
 
1717
    >>> b = a.reshape((3, 3))
 
1718
    >>> b
 
1719
    array([[-4, -3, -2],
 
1720
           [-1,  0,  1],
 
1721
           [ 2,  3,  4]])
 
1722
 
 
1723
    >>> LA.norm(a)
 
1724
    7.745966692414834
 
1725
    >>> LA.norm(b)
 
1726
    7.745966692414834
 
1727
    >>> LA.norm(b, 'fro')
 
1728
    7.745966692414834
 
1729
    >>> LA.norm(a, np.inf)
 
1730
    4
 
1731
    >>> LA.norm(b, np.inf)
 
1732
    9
 
1733
    >>> LA.norm(a, -np.inf)
 
1734
    0
 
1735
    >>> LA.norm(b, -np.inf)
 
1736
    2
 
1737
 
 
1738
    >>> LA.norm(a, 1)
 
1739
    20
 
1740
    >>> LA.norm(b, 1)
 
1741
    7
 
1742
    >>> LA.norm(a, -1)
 
1743
    -4.6566128774142013e-010
 
1744
    >>> LA.norm(b, -1)
 
1745
    6
 
1746
    >>> LA.norm(a, 2)
 
1747
    7.745966692414834
 
1748
    >>> LA.norm(b, 2)
 
1749
    7.3484692283495345
 
1750
 
 
1751
    >>> LA.norm(a, -2)
 
1752
    nan
 
1753
    >>> LA.norm(b, -2)
 
1754
    1.8570331885190563e-016
 
1755
    >>> LA.norm(a, 3)
 
1756
    5.8480354764257312
 
1757
    >>> LA.norm(a, -3)
 
1758
    nan
 
1759
 
1378
1760
    """
1379
1761
    x = asarray(x)
1380
 
    nd = len(x.shape)
1381
1762
    if ord is None: # check the default case first and handle it immediately
1382
1763
        return sqrt(add.reduce((x.conj() * x).ravel().real))
1383
1764
 
 
1765
    nd = x.ndim
1384
1766
    if nd == 1:
1385
1767
        if ord == Inf:
1386
1768
            return abs(x).max()
1387
1769
        elif ord == -Inf:
1388
1770
            return abs(x).min()
 
1771
        elif ord == 0:
 
1772
            return (x != 0).sum() # Zero norm
1389
1773
        elif ord == 1:
1390
1774
            return abs(x).sum() # special case for speedup
1391
1775
        elif ord == 2: