Logo Studenta

zPYTHON ALGEBRA LINEAL 822

¡Este material tiene más páginas!

Vista previa del material en texto

ARREGLOS CON PYTHON
ARREGLOS CON PYTHON
OPCIONES:
1. Con listas o tuplas
2. Con la librería Numpy
3. Con la librería SciPy
2
ARREGLOS CON LISTAS
VECTORES CON LISTAS
Por ejemplo:
>>> v1=[1, 2, 3, 4]
>>> v1[0] # Elemento de la posición 0
1
def leev():
print("lee un vector:")
ne = int(input('Numero de elementos= '))
v=list(range(ne)) # crea el vector
for i in range(ne): 
# i reemplaza a {0}:
v[i] = int(input(' elemento ({0}): '.format(i)))
return v
VECTORES CON LISTAS
def suma(v1, v2):
ne1=len(v1)
ne2=len(v2)
if ne1==ne2:
s=list(range(ne1)) # crea el vector
for i in range(ne1):
s[i] = v1[i] + v2[i]
print("suma:",s)
else:
print("no se suman, tamaños distintos")
def principal():
w1=leev();
w2=leev();
suma(w1, w2)
MATRIZ CON LISTAS
La matriz es, por ejemplo de 2 filas y 2 columnas:
>>> M=[ [1, 2], [3, 4] ]
>>> M[0] # Fila 0
[1, 2]
>>> M[1][0] # Fila 1, Columna 0
3
# Ejemplo: Funciones para leer y mostrar una matriz
def leer_matriz():
print('Lectura de la matriz') 
nf = int(input('Numero de filas= ')) 
nc = int(input('Numero de columnas= '))
#Creacion de la matriz nula
M = []
for i in range(nf):
M.append([0]* nc)
MATRIZ CON LISTAS
# lectura de elementos
for f in range(nf):
for c in range(nc): # f reemplaza a {0} y c a {1}:
M[f][c] = float(input(' elemento ({0},{1}): '.format(f,c)))
return M
def mostrar_matriz(M):
print(‘\nMatriz’) 
nf = len(M) # Número de filas
nc = len(M[0]) # Número de columnas
for f in range(nf):
for c in range(nc):
print(M[f][c],end='\t') # en la misma línea, tabulados
print('') # Salto de línea
MATRIZ CON LISTAS
# Producto de una matriz por un número
def producto(M, n):
nf = len(M) # Número de filas
nc = len(M[0]) # Número de columnas
for f in range(nf):
for c in range(nc):
M[f][c]= n*M[f][c]
return M
def principal2():
W=leer_matriz()
x=int(input(“Número= ”))
W=producto(W, x)
mostrar_matriz(W) 
Numpy
NumPy = NumericalPython
• NumPy es el paquete fundamental para 
computación científica con Python. 
• Contiene:
– Arreglos N-dimensionales con métodos avanzados
– Funciones de algebra lineal 
– Transformadas de Fourier 
– Numeros random avanzados
– Herramientas para integración con código C/C++/ 
Fortran
NumPy documentación
• Documentación oficial
– http://docs.scipy.org/doc/
• Libro de NumPy
– http://web.mit.edu/dvp/Public/numpybook.pdf
• Ejemplos
– https://docs.scipy.org/doc/numpy/reference/routines.html
http://docs.scipy.org/doc/
http://web.mit.edu/dvp/Public/numpybook.pdf
https://docs.scipy.org/doc/numpy/reference/routines.html
Arrays – Numerical Python (Numpy)
Las listas sirven para arreglos uni-dimensionales de pocos datos
• No pueden trabajar con operadores aritméticos (+, -, *, /, …)
• Se necesita arreglos con operaciones eficientes y herramientas
multidimensionales
• Numpy
• En general: >>> import numpy as np
• Similar a listas, con más capacidades, excepto el tamaño fijo
>>> a = [1,3,5,7,9] 
>>> print(a[2:4]) 
[5, 7] 
>>> b = [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]] 
>>> print(b[0]) 
[1, 3, 5, 7, 9] 
>>> print(b[1][2:4]) 
[6, 8] 
>>> a = [1,3,5,7,9] 
>>> b = [3,5,6,7,9]
>>> c = a + b
>>> print c
[1, 3, 5, 7, 9, 3, 5, 6, 7, 9] 
Numpy – Creación de arreglos
• Hay varias maneras de inicializar un nuevo 
arreglo en numpy, por ejemplo:
– Una lista o tupla Python 
– Usando funciones para generar arreglos 
numpy, tales como arange, linspace, etc. 
Numpy – Crear vectores
• Desde listas: numpy.array
# Como vector desde lista
>>> a = np.array([1,3,5,7,9]) 
>>> b = np.array([3,5,6,7,9])
>>> c = a + b
>>> print(c)
[4, 8, 11, 14, 18]
>>> type(c) # tipo de dato
(<type 'numpy.ndarray'>)
>>> c.shape # forma
(5,)
Numpy – Crear matrices
>>> l = [[1, 2, 3], [3, 6, 9], [2, 4, 6]] # crea una lista
>>> a = np.array(l) # convierte la lista en array 
>>>print(a) 
[[1 2 3] 
[3 6 9] 
[2 4 6]]
>>> a.shape #dimension (forma)
(3, 3) 
>>> print(a.dtype) # muestra tipo de un array 
int32 
# o crear directamente como una matriz
>>> M = np.array([[1, 2], [3, 4]])
>>> M.shape
(2,2)
>>> M.dtype
dtype('int32')
Numpy – Crear matrices
#Solo de un tipo de dato
>>> M[0,0] = "hello"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for long() with base 10: 'hello‘
# Especificando el tipo de dato
>>> M = np.array([[1, 2], [3, 4]], dtype=complex)
>>> M
array([[ 1.+0.j, 2.+0.j],
[ 3.+0.j, 4.+0.j]])
Numpy – uso de Matrices 
>>> print(a) 
[[1 2 3] 
[3 6 9] ]
>>> print(a[0]) # igual que en una lista de listas, la fila 0 
[1 2 3] 
>>> print(a[1, 2]) # una coma separa los índices
9
>>> print(a[1, 1:3]) # una parte de la matriz
[6 9] 
>>> print(a[:,1]) # la columna 1 
[2 6] 
>>> a[1, 2] = 7 # modifica un elemento
>>> print(a) 
[[1 2 3] 
[3 6 7] ] 
>>> a[:, 0] = [0, 9] # modifica la columna 0
>>> print(a) 
[[0 2 3] 
[9 6 7] ] 
Numpy – Crear arrays
• Funciones de Generación
>>> x = np.arange(0, 10, 1) # similar a range, argumentos: 
inicial, final-1, incremento
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.linspace(0, 10, 12) # inicial, final, numero de elementos
array([ 0. , 0.90909091, 1.81818182, 2.72727273, 
3.63636364, 4.54545455, 5.45454545, 6.36363636, 
7.27272727, 8.18181818, 9.09090909, 10. ])
>>> np.logspace(0, 10, 5, base=np.e) # notación exponencial
array([1.00000000e+00, 1.21824940e+01, 1.48413159e+02, 
1.80804241e+03, 2.20264658e+04])
Numpy – Crear arrays
>>> np.diag([1,2,3]) # Matriz diagonal
array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> b = np.zeros(5) # Vector de ceros 
>>> print(b) 
[0., 0., 0., 0., 0.] 
>>> b.dtype
dtype(‘float64’) 
>>> v = np.zeros(3, dtype=np.int) 
>>> v
array([0, 0, 0])
>>> v.dtype
dtype(‘int32’) 
>>> c = np.ones((3,3)) # Matriz de unos
>>> c
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
Numpy – creacion y uso de arrays
>>> d = np.arange(5) # similar a range() 
>>> print(d) 
[0 1 2 3 4] 
>>> d[1] = 9.7 
>>> print(d) # array mantiene su tipo, al cambiar elementos
[0 9 2 3 4] 
>>> print(d*0.4) # operaciones crean un nuevo array y tipo
[ 0. 3.6 0.8 1.2 1.6] 
>>> d = np.arange(5, dtype=np.float) 
>>> print(d) 
[ 0. 1. 2. 3. 4.] 
>>> np.arange(3, 7, 0.5) # arbitrarios inicio, fin e incremento
array([ 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5]) 
Numpy – array creacion y uso
>>> x, y = np.mgrid[0:3, 0:3] # como meshgrid de MATLAB
>>> x
array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2]])
>>> y
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2]]) 
>>> np.random.rand(2,3)
array([[0.53182759, 0.63440096, 0.84943179],
[0.72445532, 0.61102351, 0.72244338]])
Numpy – array creación y uso
>>> x = np.array([1,2,3,4])
>>> y = x #asignación
>>> x is y # comparación de igualdad
True
>>> id(x), id(y)
(139814289111920, 139814289111920)
>>> x[0] = 9
>>> y
array([9, 2, 3, 4])
>>> x[0] = 1
>>> z = x[:]
>>> x is z
False
>>> id(x), id(z)
(139814289111920, 139814289112080)
>>> x[0] = 8
>>> z
array([8, 2, 3, 4])
Dos ndarrays son mutables y ocupan la misma posición de memoria:
Numpy – array creación y uso
>>> x = np.array([1,2,3,4])
>>> y = x.copy()
>>> x is y
False
>>> id(x), id(y)
(139814289111920, 139814289111840)
>>> x[0] = 9
>>> x
array([9, 2, 3, 4])
>>> y
array([1, 2, 3, 4])
Numpy – array creación y uso
>>> a = np.arange(4.0) 
>> a
array([0., 1., 2., 3.])
>>> b = a * 23.4 
>>> b
array([ 0. , 23.4, 46.8, 70.2])
>>> c = b/(a+1) 
>>> c += 10 
>>> print c 
[ 10. 21.7 25.6 27.55] 
>>> arr = np.arange(100, 200) 
>>> seleccion = [5, 25, 50, 75, -5] 
>>> print(arr[seleccion]) #puede usar lista enteros como índices
[105, 125, 150, 175, 195] 
Numpy – array creación y uso
>>> arr = np.arange(10, 20)
>> arr
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> div_por_3 = arr%3 == 0 # comparación produce un 
arreglo con dato boolean
>>> print(div_por_3) 
[ False False True False False True False False True False] 
>>> print(arr[div_por_3])# puede usarse una lista boolean
como indices (considera los True) 
[12 15 18] 
# Cambiando las dimensiones con reshape
>>> arr = np.arange(10, 20) . reshape((2,5))
[[10 11 12 13 14]
[15 16 17 18 19]]
Numpy – métodos array
>>> arr.sum() # sumatoria
145 
>>> arr.mean() # promedio
14.5 
>>> arr.std() # desviación estándar
2.8722813232690143 
>>> arr.max() # mayor
19 
>>> arr.min() # menor
10 
>>> div_by_3.all() # todos son True
False 
>>> div_by_3.any() # alguno es True
True
>>> div_by_3.sum() # sumatoria (No.) de True
3
>>> div_by_3.nonzero() # posiciones de True
(array([2, 5, 8]), dtype=int64),) 
Numpy – métodos array - sorting
>>> a = np.array([4.5, 2.3, 6.7, 1.2, 1.8, 5.5]) 
>>> a.sort() # ordena el array físicamente, lo modifica
>>> print(a) 
[ 1.2 1.8 2.3 4.5 5.5 6.7] 
>>> x = np.array([4.5, 2.3, 6.7, 1.2, 1.8, 5.5]) 
>>> np.sort(x) # ordena sin modificar el array x
array([ 1.2, 1.8, 2.3, 4.5, 5.5, 6.7]) 
>>> print(x) 
[ 4.5 2.3 6.7 1.2 1.8 5.5] 
>>> s = x.argsort() # indice de elementos por orden
>>> s 
array([3, 4, 1, 0, 5, 2])
>>> x[s] # muestra x ordenado, según s
array([ 1.2, 1.8, 2.3, 4.5, 5.5, 6.7]) 
PROBLEMAS
2. PROBAR LOS EJEMPLOS (DE LAS DIAPOSITIVAS DE 
ESTA Y LA ANTERIOR CLASE)
3. Programa para restar dos matrices, representadas 
con listas
28
GRACIAS

Continuar navegando