Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

NOTEBOOKS TUTORIAL SAGEMATH

Views: 4549
%auto typeset_mode(True, display=True)

ÁLGEBRA LINEAR

Aneis

Some common Sage rings and fields

ZZ integers, ring

QQ rationals, field

AA, QQbar algebraic number fields, exact

RDF real double field, inexact

CDF complex double field, inexact

RR 53-bit reals, inexact, not same as RDF

RealField(400) 400-bit reals, inexact

CC, ComplexField(400) complexes, too

RIF real interval field

GF(2) mod 2, field, specialized implementations

GF(p) == FiniteField(p) p prime, field

Integers(6) integers mod 6, ring only

CyclotomicField(7) rationals with 7th root of unity √QuadraticField(-5, ’x’) rationals with x= −5

SR ring of symbolic expressions

Vetores

v = vector([1, 0]) u = vector([0, 1]) t = vector([-1,-2]) v;u;t
(1, 0) (0, 1) (-1, -2)
type(v)
<type 'sage.modules.vector_integer_dense.Vector_integer_dense'>

Gráfico de vetores 2D e 3D

Visualização 2D

plot(v,color="red", figsize = (4,4),gridlines="minor") + plot(u) + plot(t,color="green")

Campo de vetores resultante 2D

var('u,v') plot_vector_field((u,v),(u,1,5),(v,1,5), figsize=(4,4), gridlines="minor")

Vizualização 3D

w = vector([1, 0, 0]); r = vector([0,1, 0]); s = vector([0,0, 1]); w;r;s;
(1, 0, 0) (0, 1, 0) (0, 0, 1)
plot(w,color="red", figsize = (4,4), thickness=3) + plot(r, thickness=3) + plot(s,color="green", thickness=3)
3D rendering not yet implemented

Operações com Vetores

** Soma e Subtração de Vetores**

v = vector([1, 0]); u = vector([0, 1]); t = vector([-1,-2]); Som = v + u + t; Sub = v - u - t v; u; t; Som; Sub
(1,0)\displaystyle \left(1,\,0\right)
(0,1)\displaystyle \left(0,\,1\right)
(1,2)\displaystyle \left(-1,\,-2\right)
(0,1)\displaystyle \left(0,\,-1\right)
(2,1)\displaystyle \left(2,\,1\right)

** Multiplicação por escalar**

v = vector([1, 0]); 2*v
(2,0)\displaystyle \left(2,\,0\right)

Multiplicação elemento por elemento entre vetores

v = vector([1, 0]) u = vector([0, 1]) # Divisão por escalar v = vector([1, 0]) v/2 v.pairwise_product(u)
(12,0)\displaystyle \left(\frac{1}{2},\,0\right)
(0,0)\displaystyle \left(0,\,0\right)

Divisão por escalar

v = vector([1, 0]) v/2
(1/2, 0)

Divisão elemento por elemento entre vetores

v = vector([1, 0]) u = vector([0, 1])

Potencia elemento por elemento

v = vector([1, 2]) u = vector([3, 4]) v.apply_map(lambda x: x^2)
(1,4)\displaystyle \left(1,\,4\right)

Transposição

v = vector([1, 0]) v.column()
(10)\displaystyle \left(\begin{array}{r} 1 \\ 0 \end{array}\right)

Vetor aletório

Para definir um vetor aleatório é necessário definir o tipo (inteiro, real, complexo...).

# vetor do tipo racional Va = random_vector(QQ, 3) #vetor do tipo inteiro Vab = random_vector(ZZ, 3) Va ; Vab
(0,35,1)\left(0,\,\frac{3}{5},\,1\right)
(1,2,2)\left(1,\,2,\,2\right)

Max e Min de Vetores

v = vector([1 , 5, 9])

Valor máximo de um vetor e indicesr

max(v)
99
# Testando se o indice 3 corresponde ao elemento de maior valor do vetor v = [1 2 3]. # O valor true no teste de igualdade corresponde a verdadeiro

Valor mínimo de um vetor

min(v)
11
# Valor minimo de um vetor e indice
#8a2960b1-2fd0-42b3-b594-593585b09c6f # O valor true no teste de igualdade corresponde a verdadeiro

Produto interno: somente vetores coluna

Aqui o uso do transpose ou v' nao funciona

v = vector([1, 0]) u = vector([0, 1]) v.inner_product(u) ; v.dot_product(u)
00
00

Produto externo ou vetorial

vv = vector([1, 0, 0]) uu = vector([0, 1, 0]) vv.cross_product(uu)
(0,0,1)\left(0,\,0,\,1\right)

Multiplicação de Vetores

Multiplicação v(linhas_v,colunas_v) * u(linhas_u,colunas_u) , só é possível se colunas_v = linhas_u ou seja se o número de colunas de v for igual ao númer de linhas de colunas de u resultando em um vetor de m_v linhas e n_u colunas

v = vector([1, 1]) u = vector([-1, -1]) u*v
2-2

Matrizes

matrix([[0, -1, -1], [1, 1, 1], [2, 4, 1]])
(011111241)\left(\begin{array}{rrr} 0 & -1 & -1 \\ 1 & 1 & 1 \\ 2 & 4 & 1 \end{array}\right)

Gráfico de uma matriz

Ma = random_matrix(RDF,5) Ma
[ -0.1032382412035342 -0.38201845069804974 -0.17885398673138297 0.008224366026518881 -0.12773340414320855] [ 0.10758505605507218 -0.7508149483865172 -0.3866458014346952 0.9386922164849179 0.23506261592168642] [ 0.13525025993116557 -0.11677853435275609 -0.0483774234967167 0.8014679287942608 0.34198819292981586] [ 0.705771084626531 0.4106798868579391 0.523187920773257 0.9813709199220866 0.012997233253571494] [ 0.3857670171669647 0.07495819679124693 -0.5623436716920467 -0.9591569054965412 -0.6371694367938718]
Ma.plot(cmap='Blues',vmin=min(min(Ma)), vmax=ceil(max(max(Ma))), colorbar=true, figsize=(4,3))

Operação Algébricas com Matrizes

A = matrix([[0, -1, -1], [1, 1, 1], [2, 4, 1]]) B = matrix([[1.1, 0.0, 1.8], [-1.7, 9.6, 1.0], [7.9, 4.6, -5.5]]) A ; B
(011111241)\displaystyle \left(\begin{array}{rrr} 0 & -1 & -1 \\ 1 & 1 & 1 \\ 2 & 4 & 1 \end{array}\right)
(1.100000000000000.0000000000000001.800000000000001.700000000000009.600000000000001.000000000000007.900000000000004.600000000000005.50000000000000)\displaystyle \left(\begin{array}{rrr} 1.10000000000000 & 0.000000000000000 & 1.80000000000000 \\ -1.70000000000000 & 9.60000000000000 & 1.00000000000000 \\ 7.90000000000000 & 4.60000000000000 & -5.50000000000000 \end{array}\right)
type(A) ; type(B)
<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'> <type 'sage.matrix.matrix_generic_dense.Matrix_generic_dense'>

Soma e Subtração de Matrizes

A+B
(1.100000000000001.000000000000000.8000000000000000.70000000000000010.60000000000002.000000000000009.900000000000008.600000000000004.50000000000000)\displaystyle \left(\begin{array}{rrr} 1.10000000000000 & -1.00000000000000 & 0.800000000000000 \\ -0.700000000000000 & 10.6000000000000 & 2.00000000000000 \\ 9.90000000000000 & 8.60000000000000 & -4.50000000000000 \end{array}\right)
A-B
(1.100000000000001.000000000000002.800000000000002.700000000000008.600000000000000.0000000000000005.900000000000000.6000000000000006.50000000000000)\displaystyle \left(\begin{array}{rrr} -1.10000000000000 & -1.00000000000000 & -2.80000000000000 \\ 2.70000000000000 & -8.60000000000000 & 0.000000000000000 \\ -5.90000000000000 & -0.600000000000000 & 6.50000000000000 \end{array}\right)

Matriz aleatória

C = random_matrix(RR,3,3) D = random_matrix(ZZ,3,2) C ; D
(0.8162358685045350.4595794719752090.3595465318077270.2806310920462120.9906706742355390.8870337356775540.9161098171197490.7865005281049730.749626359634091)\left(\begin{array}{rrr} -0.816235868504535 & 0.459579471975209 & 0.359546531807727 \\ -0.280631092046212 & 0.990670674235539 & 0.887033735677554 \\ -0.916109817119749 & -0.786500528104973 & -0.749626359634091 \end{array}\right)
(162015)\left(\begin{array}{rr} 1 & -6 \\ 2 & 0 \\ 1 & 5 \end{array}\right)
type(C) ; type(D)
<type 'sage.matrix.matrix_generic_dense.Matrix_generic_dense'> <type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'>

Determinante

A = matrix([[0, -1, -1], [1, 1, 1], [2, 4, 1]]) A.det() ; det(A)
3-3
3-3

Cofatores

A = matrix([[0, -1, -1], [1, 1, 1], [2, 4, 1]]) A.adjoint()
(330121221)\left(\begin{array}{rrr} -3 & -3 & 0 \\ 1 & 2 & -1 \\ 2 & -2 & 1 \end{array}\right)

Multiplicação de Matrizes

Multiplicação Ma(linhas_Ma,colunas_Ma) * Mb(linhas_Mb,colunas_Mb) , só é possível se colunas_Ma = linhas_Mb ou seja se o número de colunas de Ma for igual ao número de linhas de Mb resultando em uma matriz de Ma_linhas e Mb_colunas

A = matrix([[0, -1, -1], [1, 1, 1], [2, 4, 1]]) B = matrix([[1.1, 0.0, 1.8], [-1.7, 9.6, 1.0], [7.9, 4.6, -5.5]]) A*B
(6.2000000000000014.20000000000004.500000000000007.3000000000000014.20000000000002.700000000000003.3000000000000043.00000000000002.10000000000000)\displaystyle \left(\begin{array}{rrr} -6.20000000000000 & -14.2000000000000 & 4.50000000000000 \\ 7.30000000000000 & 14.2000000000000 & -2.70000000000000 \\ 3.30000000000000 & 43.0000000000000 & 2.10000000000000 \end{array}\right)

Matrizes especiais

# matriz de zeros Mzeros_A = matrix(3, 3, 0) Mzeros_B = zero_matrix(3,3) Mzeros_A; Mzeros_B
(000000000)\displaystyle \left(\begin{array}{rrr} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{array}\right)
(000000000)\displaystyle \left(\begin{array}{rrr} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{array}\right)
# matriz de uns Muns = ones_matrix(3,3) Muns
(111111111)\displaystyle \left(\begin{array}{rrr} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{array}\right)
# matriz identidade Miden_A = matrix(3, 3, 1) Miden_B = identity_matrix(3,3) Miden_A; Miden_B
(100010001)\left(\begin{array}{rrr} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{array}\right)
(100010001)\left(\begin{array}{rrr} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{array}\right)
#matriz diagonal com termos definidos Mdiag_A = diagonal_matrix([2, 1.3, 5]) Mdiag_B = matrix(QQ, 3, 3, 8) Mdiag_A ; Mdiag_B
(2.000000000000000.0000000000000000.0000000000000000.0000000000000001.300000000000000.0000000000000000.0000000000000000.0000000000000005.00000000000000)\left(\begin{array}{rrr} 2.00000000000000 & 0.000000000000000 & 0.000000000000000 \\ 0.000000000000000 & 1.30000000000000 & 0.000000000000000 \\ 0.000000000000000 & 0.000000000000000 & 5.00000000000000 \end{array}\right)
(800080008)\left(\begin{array}{rrr} 8 & 0 & 0 \\ 0 & 8 & 0 \\ 0 & 0 & 8 \end{array}\right)

Mapping em uma matriz

Mb = matrix([[1,2],[3,4]]) Mb
(1234)\displaystyle \left(\begin{array}{rr} 1 & 2 \\ 3 & 4 \end{array}\right)
Mb.apply_map(lambda x: x^2)
(14916)\left(\begin{array}{rr} 1 & 4 \\ 9 & 16 \end{array}\right)
%md #### **Simplificação de uma matriz**

Simplificação de uma matriz

# Matriz dos coeficietes e vetor dos termos independentes MA = matrix(RDF,[[8.0,9.1,1.9],[0.5,5.5,3.6],[8.9,1.0,6.1]]) MB = vector(RDF,[8.1,-3.0,7.5]) MA; MB
(8.09.11.90.55.53.68.91.06.1)\left(\begin{array}{rrr} 8.0 & 9.1 & 1.9 \\ 0.5 & 5.5 & 3.6 \\ 8.9 & 1.0 & 6.1 \end{array}\right)
(8.1,3.0,7.5)\left(8.1,\,-3.0,\,7.5\right)
# Matriz ampliada MA.augment(MB,subdivide=True)
(8.09.11.98.10.55.53.63.08.91.06.17.5)\left(\begin{array}{rrr|r} 8.0 & 9.1 & 1.9 & 8.1 \\ 0.5 & 5.5 & 3.6 & -3.0 \\ 8.9 & 1.0 & 6.1 & 7.5 \end{array}\right)

simplificando o a Matriz ampliada

MA.augment(MB).rref()
(1.00.00.01.387491066090.01.00.00.1695036392010.00.01.00.767076532622)\left(\begin{array}{rrrr} 1.0 & 0.0 & 0.0 & 1.38749106609 \\ 0.0 & 1.0 & 0.0 & -0.169503639201 \\ 0.0 & 0.0 & 1.0 & -0.767076532622 \end{array}\right)
MA.pivots()
(00, 11, 22)

Sistemas Lineares

Resolvenddo o sistema

Divisão à Direita

MA = matrix(RDF,[[8.0,9.1,1.9],[0.5,5.5,3.6],[8.9,1.0,6.1]]) MB = vector(RDF,[8.1,-3.0,7.5]) MA ; MB
(8.09.11.90.55.53.68.91.06.1)\displaystyle \left(\begin{array}{rrr} 8.0 & 9.1 & 1.9 \\ 0.5 & 5.5 & 3.6 \\ 8.9 & 1.0 & 6.1 \end{array}\right)
(8.1,3.0,7.5)\displaystyle \left(8.1,\,-3.0,\,7.5\right)
X = MA\MB X
(1.38749106609,0.169503639201,0.767076532622)\displaystyle \left(1.38749106609,\,-0.169503639201,\,-0.767076532622\right)
X = MA.solve_right(MB) X
(1.38749106609,0.169503639201,0.767076532622)\displaystyle \left(1.38749106609,\,-0.169503639201,\,-0.767076532622\right)

Cálculo Optimizado

  • Utilizando o SageMath

# definindo as matrizes A1 = random_matrix(RR,500,500) B1 = random_vector(RR,500) A2 = random_matrix(RDF,500,500) B2 = random_vector(RDF,500)
# Matrizes Reais %time xx1 =A1\B1 xx1[5]
-2.00037082443103 CPU time: 55.86 s, Wall time: 56.17 s
# Matrizes Reais %time x1 = A1.solve_right(B1) x1[5]
0.469860978000125 CPU time: 29.08 s, Wall time: 29.38 s
# Matrizes RDF %time xx2 =A2\B2 xx2[5]
-0.7764439660179416 CPU time: 0.02 s, Wall time: 0.03 s
# Matrizes RDF %time x2 = A2.solve_right(B2) x2[5]
-0.7764439660179416 CPU time: 0.04 s, Wall time: 0.04 s

Comparação com outros Softwares

Julia Octave MatLab Julia Python Sage RDF   
      2.326s*  3.38s A/B : 8.480s*

Linalg: 8.523s*

* tempo médio em segundos numa máquina I5 Haswell, 8GB Ram, Linux NETRunner 17, SageMath 7.0

Aritmética em RR(reais) é mais lento do que aritmética com tipos C nativos. 

Decomposição LU

Ax = b

A = LU

PA = LU

P is a square permutation matrix, of siz, so is all zeroes, but with exactly a single one in each row and each column. L is lower-triangular, square of siz, with every diagonal entry equal to one. U is upper-triangular with size, i.e. entries below the “diagonal” are all zero.
MA = matrix(RDF,[[8.0,9.1,1.9],[0.5,5.5,3.6],[8.9,1.0,6.1]]) MB = vector(RDF,[8.1,-3.0,7.5]) MA ; MB
(8.09.11.90.55.53.68.91.06.1)\left(\begin{array}{rrr} 8.0 & 9.1 & 1.9 \\ 0.5 & 5.5 & 3.6 \\ 8.9 & 1.0 & 6.1 \end{array}\right)
(8.1,3.0,7.5)\left(8.1,\,-3.0,\,7.5\right)
P, L , U = MA.LU() P; L; U
(0.00.01.01.00.00.00.01.00.0)\left(\begin{array}{rrr} 0.0 & 0.0 & 1.0 \\ 1.0 & 0.0 & 0.0 \\ 0.0 & 1.0 & 0.0 \end{array}\right)
(1.00.00.00.8988764044941.00.00.05617977528090.6637895602141.0)\left(\begin{array}{rrr} 1.0 & 0.0 & 0.0 \\ 0.898876404494 & 1.0 & 0.0 \\ 0.0561797752809 & 0.663789560214 & 1.0 \end{array}\right)
(8.91.06.10.08.201123595513.583146067420.00.05.63575832306)\left(\begin{array}{rrr} 8.9 & 1.0 & 6.1 \\ 0.0 & 8.20112359551 & -3.58314606742 \\ 0.0 & 0.0 & 5.63575832306 \end{array}\right)
# Testando L*U
(8.91.06.18.09.11.90.55.53.6)\left(\begin{array}{rrr} 8.9 & 1.0 & 6.1 \\ 8.0 & 9.1 & 1.9 \\ 0.5 & 5.5 & 3.6 \end{array}\right)

Método de Cholesky

Este método se aplica quando a matriz dos coeficientes A é simétrica (A=At)(A = A^t) e definida positiva. Nesta situação, a matriz A pode ser fatorada em A=LU=LLtA=LU=LL^t.

MC = matrix([[4,2,14],[2,17,-5],[14,-5,83]]) MC
(4214217514583)\displaystyle \left(\begin{array}{rrr} 4 & 2 & 14 \\ 2 & 17 & -5 \\ 14 & -5 & 83 \end{array}\right)
MC.transpose() == MC
True\displaystyle \mathrm{True}
MC.cholesky()
(200140735)\displaystyle \left(\begin{array}{rrr} 2 & 0 & 0 \\ 1 & 4 & 0 \\ 7 & -3 & 5 \end{array}\right)

AutoVetores e AutoValores

A = matrix([[0, 4], [-1, 0]]) A
(0410)\renewcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr} 0 & 4 \\ -1 & 0 \end{array}\right)
A.eigenvalues ()
[21,21]\renewcommand{\Bold}[1]{\mathbf{#1}}\left[-2 \sqrt{-1}, 2 \sqrt{-1}\right]
A.eigenmatrix_left()
A.eigenmatrix_right()

%%% Fim Algebra linear %%%