Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168742
Image: ubuntu2004
# Numpy == Numerical Python # Scipy == Scientific python # from scipy import * import numpy as np # Numpy arrays a = np.array([1,2,3,4]) b = np.array([a.copy(), a.copy()]) print 'a = ', a, '\n', 'b = ', b
a = [1 2 3 4] b = [[1 2 3 4] [1 2 3 4]]
a * 2
array([2, 4, 6, 8])
a + 2
array([3, 4, 5, 6])
a + b
array([[2, 4, 6, 8], [2, 4, 6, 8]])
c= np.arange(4) print c print c * a
[0 1 2 3] [ 0 2 6 12]
print c print c**2
[0 1 2 3] [0 1 4 9]
d = np.ones(4) print d
[ 1. 1. 1. 1.]
e = np.zeros(4) print e
[ 0. 0. 0. 0.]
print(a)
[1 2 3 4]
np.sum(a)
10
np.var(a)
1.25
np.mean(a)
2.5
np.std(a)
1.1180339887498949
prod(a)
24
np.max(a), np.min(a)
(4, 1)
a.shape
(4,)
a.reshape(2,2)
array([[1, 2], [3, 4]])
a.reshape(1,4)
array([[1, 2, 3, 4]])
f = a.reshape(2,2)
f[0]
array([1, 2])
f[0,1]
2
f[1,1]
4
g = f.tolist() print g
[[1, 2], [3, 4]]
np.array(g)
array([[1, 2], [3, 4]])
np.array(g).reshape(4,)
array([1, 2, 3, 4])
np.identity(2)
array([[ 1., 0.], [ 0., 1.]])
np.identity(4)
array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]])
np.linspace(1,10,10)
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
np.linspace(1,10,19)
array([ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5, 10. ])
# Numpy Matrices h = np.mat([[1,2,3],[4,5,6],[7,8,9]]) print h
[[1 2 3] [4 5 6] [7 8 9]]
h * 2
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_69.py", line 9, in <module> exec compile(ur'open("___code___.py","w").write("# -*- coding: utf-8 -*-\n" + _support_.preparse_worksheet_cell(base64.b64decode("aCAqIDI="),globals())+"\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpsbB7PX/___code___.py", line 3, in <module> exec compile(ur'h * _sage_const_2 ' + '\n', '', 'single') File "", line 1, in <module> File "element.pyx", line 1339, in sage.structure.element.RingElement.__mul__ (sage/structure/element.c:10826) File "coerce.pyx", line 765, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (sage/structure/coerce.c:6988) TypeError: unsupported operand parent(s) for '*': '<class 'numpy.core.defmatrix.matrix'>' and 'Integer Ring'
i = np.array([1,2,3]) h * i
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_73.py", line 9, in <module> exec compile(ur'open("___code___.py","w").write("# -*- coding: utf-8 -*-\n" + _support_.preparse_worksheet_cell(base64.b64decode("aSA9IG5wLmFycmF5KFsxLDIsM10pCmggKiBp"),globals())+"\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpfEDlJ4/___code___.py", line 4, in <module> exec compile(ur'h * i' + '\n', '', 'single') File "", line 1, in <module> File "/usr/local/sage2/local/lib/python2.6/site-packages/numpy/core/defmatrix.py", line 290, in __mul__ return N.dot(self, asmatrix(other)) ValueError: objects are not aligned
j = np.array([[1],[2],[3]]) print j
[[1] [2] [3]]
h * j
matrix([[14], [32], [50]])
j * h
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_81.py", line 9, in <module> exec compile(ur'open("___code___.py","w").write("# -*- coding: utf-8 -*-\n" + _support_.preparse_worksheet_cell(base64.b64decode("aiAqIGg="),globals())+"\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpWExL0u/___code___.py", line 2, in <module> exec compile(ur'j * h' + '\n', '', 'single') File "", line 1, in <module> File "/usr/local/sage2/local/lib/python2.6/site-packages/numpy/core/defmatrix.py", line 296, in __rmul__ return N.dot(other, self) ValueError: objects are not aligned
k=np.array(h) print(k)
[[1 2 3] [4 5 6] [7 8 9]]
k * j
array([[ 1, 2, 3], [ 8, 10, 12], [21, 24, 27]])
np.dot(k,j)
array([[14], [32], [50]])
print h
[[1 2 3] [4 5 6] [7 8 9]]
transpose(h)
matrix([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
h.T
matrix([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
# inverse of h h.I
matrix([[ -4.50359963e+15, 9.00719925e+15, -4.50359963e+15], [ 9.00719925e+15, -1.80143985e+16, 9.00719925e+15], [ -4.50359963e+15, 9.00719925e+15, -4.50359963e+15]])
np.random.rand()
0.96553984583384866
l = np.mat(np.random.rand(5,5)) print l
[[ 0.14539722 0.03031367 0.30173718 0.33242993 0.55719099] [ 0.2785615 0.97509371 0.23910018 0.34094224 0.07870607] [ 0.61004798 0.75300478 0.5690051 0.61338394 0.07358492] [ 0.82351098 0.47577046 0.1977098 0.07856082 0.80707922] [ 0.78602508 0.64364376 0.18511759 0.57374703 0.4664508 ]]
# Solves a set of linear equations np.linalg.solve(h,j)
array([[-0.33333333], [ 0.66666667], [ 0. ]])
# Calculates the eigenvalue linalg.eig(h)
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_100.py", line 9, in <module> exec compile(ur'open("___code___.py","w").write("# -*- coding: utf-8 -*-\n" + _support_.preparse_worksheet_cell(base64.b64decode("IyBDYWxjdWxhdGVzIHRoZSBlaWdlbnZhbHVlIAoKbGluYWxnLmVpZyhoKQ=="),globals())+"\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpD7XXVr/___code___.py", line 4, in <module> exec compile(ur'linalg.eig(h)' + '\n', '', 'single') File "", line 1, in <module> NameError: name 'linalg' is not defined
np.linalg.eig??

File: /usr/local/sage2/local/lib/python2.6/site-packages/numpy/linalg/linalg.py

Source Code (starting at line 734):

def eig(a):
    """
    Compute eigenvalues and right eigenvectors of an array.

    Parameters
    ----------
    a : array_like, shape (M, M)
        A complex or real 2-D array.

    Returns
    -------
    w : ndarray, shape (M,)
        The eigenvalues, each repeated according to its multiplicity.
        The eigenvalues are not necessarily ordered, nor are they
        necessarily real for real matrices.
    v : ndarray, shape (M, M)
        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
        the column ``v[:,i]``.

    Raises
    ------
    LinAlgError
        If the eigenvalue computation does not converge.

    See Also
    --------
    eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
    eig : eigenvalues and right eigenvectors for non-symmetric arrays
    eigvals : eigenvalues of non-symmetric array.

    Notes
    -----
    This is a simple interface to the LAPACK routines dgeev and zgeev
    that compute the eigenvalues and eigenvectors of general real and
    complex arrays respectively.

    The number `w` is an eigenvalue of a if there exists a vector `v`
    satisfying the equation ``dot(a,v) = w*v``. Alternately, if `w` is
    a root of the characteristic equation ``det(a - w[i]*I) = 0``, where
    `det` is the determinant and `I` is the identity matrix. The arrays
    `a`, `w`, and `v` satisfy the equation ``dot(a,v[i]) = w[i]*v[:,i]``.

    The array `v` of eigenvectors may not be of maximum rank, that is, some
    of the columns may be dependent, although roundoff error may
    obscure that fact. If the eigenvalues are all different, then theoretically
    the eigenvectors are independent. Likewise, the matrix of eigenvectors
    is unitary if the matrix `a` is normal, i.e., if
    ``dot(a, a.H) = dot(a.H, a)``.

    The left and right eigenvectors are not necessarily the (Hermitian)
    transposes of each other.

    """
    a, wrap = _makearray(a)
    _assertRank2(a)
    _assertSquareness(a)
    _assertFinite(a)
    a, t, result_t = _convertarray(a) # convert to double or cdouble type
    real_t = _linalgRealType(t)
    n = a.shape[0]
    dummy = zeros((1,), t)
    if isComplexType(t):
        # Complex routines take different arguments
        lapack_routine = lapack_lite.zgeev
        w = zeros((n,), t)
        v = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork,), t)
        rwork = zeros((2*n,), real_t)
        results = lapack_routine('N', 'V', n, a, n, w,
                                 dummy, 1, v, n, work, -1, rwork, 0)
        lwork = int(abs(work[0]))
        work = zeros((lwork,), t)
        results = lapack_routine('N', 'V', n, a, n, w,
                                 dummy, 1, v, n, work, lwork, rwork, 0)
    else:
        lapack_routine = lapack_lite.dgeev
        wr = zeros((n,), t)
        wi = zeros((n,), t)
        vr = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork,), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi,
                                  dummy, 1, vr, n, work, -1, 0)
        lwork = int(work[0])
        work = zeros((lwork,), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi,
                                  dummy, 1, vr, n, work, lwork, 0)
        if all(wi == 0.0):
            w = wr
            v = vr
            result_t = _realType(result_t)
        else:
            w = wr+1j*wi
            v = array(vr, w.dtype)
            ind = flatnonzero(wi != 0.0)      # indices of complex e-vals
            for i in range(len(ind)/2):
                v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]]
                v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]]
            result_t = _complexType(result_t)

    if results['info'] > 0:
        raise LinAlgError, 'Eigenvalues did not converge'
    vt = v.transpose().astype(result_t)
    return w.astype(result_t), wrap(vt)
m = np.mat([[1,2,3],[0,.9,0],[0,0,0.5]]) np.linalg.eig(m)
(array([ 1. , 0.9, 0.5]), matrix([[ 1. , -0.99875234, -0.98639392], [ 0. , 0.04993762, 0. ], [ 0. , 0. , 0.16439899]]))