{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## CS 132 Homework 03 A \n", "\n", "\n", "### Due Wednesday July 28th at Midnight (1 minute after 11:59pm) in Gradescope (with grace period of 6 hours)\n", "### Homeworks may be submitted up to 24 hours late with a 10% penalty (same grace period)\n", "\n", "### Homework 03 B will be posted Friday before lecture\n", "\n", "\n", "Please read through the entire notebook, reading the expository material and then do the problems, following the instuctions to try various features; among the exposition of various features of Python there\n", "are three problems which will be graded. The homework is worth 30 points. \n", "\n", "You will need to complete this notebook and then convert to a PDF file in order to submit to Gradescope. Instructions are given here:\n", "\n", "https://www.cs.bu.edu/fac/snyder/cs132/HWSubmissionInstructions.html\n", "\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# Here are some imports which will be used in the code in the rest of the lab \n", "\n", "# Imports used for the code in CS 237\n", "\n", "import numpy as np # arrays and functions which operate on arrays\n", "\n", "import matplotlib.pyplot as plt # normal plotting\n", "\n", "\n", "# NOTE: You may not use any other libraries than those listed here without explicit permission." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Preface to Lab Problems\n", "\n", "The following cell contains an implementation of the Gaussian Elimination code we have developed\n", "in the last two weeks. Please read through the comments to understand how to use the various functions" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "# Gaussian Elimination\n", "\n", "# number of digits of precision to print out\n", "\n", "prec = 4\n", "\n", "########################################################################################################\n", "\n", "# Returns the Row Echelon (upper triangular) form\n", "\n", "def forwardElimination(A,traceLevel=0):\n", " \n", " A = (np.copy(A)).astype(float)\n", " \n", " if (traceLevel > 0):\n", " print(\"Running Forward Elimination on:\\n\")\n", " print(np.round(A, decimals=4),\"\\n\")\n", " print()\n", " \n", " (numRows,numCols) = A.shape\n", " \n", " # r = row we are currently working on pivot value is A[r][c]\n", " r = 0 \n", " for c in range(numCols): # solve for variable in column c \n", " # find row in column c with first non-zero element, and exchange with row r \n", " r1 = r\n", " while(r1 < numRows):\n", " if (not np.isclose(A[r1][c],0.0)): # A[r1][c] is first non-zero element at or below r in column c\n", " break\n", " r1 += 1\n", " \n", " if(r1 == numRows): # all zeros below r in this column\n", " continue # go on to the next column, but still working on same row \n", " \n", " if(r1 != r): \n", " # exchange rows r1 and r\n", " A[[r1,r],:] = A[[r,r1],:] \n", " if (traceLevel == 2): \n", " print(\"Exchange R\" + str(r1+1) + \" and R\" + str(r+1) + \"\\n\") \n", " print(np.round(A, decimals=4)) \n", " print() \n", "\n", " # now use pivot A[r][c] to eliminate all vars in this column below row r\n", " for r2 in range(r+1,numRows):\n", " rowReduce(A,r,c,r2,traceLevel)\n", " \n", " r += 1 \n", " if (r >= numRows):\n", " break\n", " \n", " return A\n", "\n", "# for pivot A[r][c], eliminate variable in location A[r2][c] in row r2 using row operations\n", "\n", "def rowReduce(A,r,c,r2,traceLevel=0):\n", "\n", " if(not np.isclose(A[r2][c],0.0)):\n", "\n", " factor = -A[r2][c]/A[r][c] \n", " A[r2] += factor * A[r]\n", " \n", " if(traceLevel == 2):\n", " print(\"R\" + str(r2+1) + \" += \" + str(np.around(factor,prec)) + \"*R\" + str(r+1) + \"\\n\") \n", " print(np.round(A, decimals=4))\n", " print()\n", "\n", "# Take a Row Echelon Form and return a Reduced Row Echelon Form\n", "\n", "def backwardSubstitute(A,augmented=True,traceLevel=0): \n", " \n", " numRows,numCols = A.shape\n", " \n", " if (A.dtype != 'float64'):\n", " A = A.astype(float)\n", "\n", " # now back-substitute the variables from bottom row to top\n", " if (traceLevel > 0):\n", " print(\"Creating Reduced Row Echelon Form...\\n\") \n", "\n", " for r in range(numRows):\n", "\n", " # find variable in this row\n", " for c in range(numCols):\n", " if(not np.isclose(A[r][c],0.0)):\n", " break \n", " \n", " if ((augmented and c >= numCols-1) or (c >= numCols)): # inconsistent or redundant row\n", " continue \n", " \n", " # A[r][c] is variable to eliminate\n", " \n", " factor = A[r][c]\n", " \n", " if (np.isclose(factor,0.0)): # already eliminated\n", " continue\n", " \n", " if(not np.isclose(factor,1.0)): \n", " A[r] *= 1/factor\n", " if (traceLevel == 2):\n", " print(\"R\" + str(r+1) + \" = R\" + str(r+1) + \"/\" + str(np.around(factor,prec)) + \"\\n\") \n", " print(np.round(A, decimals=4))\n", " print()\n", "\n", " for r2 in range(r): \n", " rowReduce(A,r,c,r2,traceLevel)\n", " \n", " return A \n", "\n", " \n", "# try to find row of all zeros except for last column, in augmented matrix. \n", "\n", "def noSolution(A):\n", " numRows,numCols = A.shape\n", " for r in range(numRows-1,-1,-1): # start from bottom, since inconsistent rows end up there\n", " for c in range(numCols):\n", " if(not np.isclose(A[r][c],0.0)): # found first non-0 in this row\n", " if(c == numCols-1):\n", " return True\n", " else:\n", " break\n", " return False\n", "\n", "########################################################################################################\n", "\n", "# Runs GE and returns a reduced row echelon form\n", "\n", "# If b == None assumes that A is NOT an augmented matrix, and runs GE and returns Reduced Row Echelon Form\n", "\n", "# If b is a column matrix then adjoins it to A and runs GE;\n", "# Always returns the Reduced Row Echelon Form\n", "# If inconsistent then also prints out \"Inconsistent!\"\n", "\n", "# If b is a length n array instead of a 1 x n array (column vector)\n", "# b will be converted to a column vector, for convenience. \n", "\n", "# traceLevel 0 will not print anything out during the run\n", "# traceLevel 1 will print out various stages of the process and the intermediate matrices\n", "# traceLevel 2 will also print out the row operations used at each step. \n", "\n", "# If you want to produce an Echelon Form (NOT reduced), then use forwardElimination instead. \n", "\n", "# See examples for more explanation of how to use this\n", "\n", "def GaussianElimination(A,b=None, traceLevel = 0):\n", " if( type(b) != type(None)):\n", " if( (A.shape)[0] == 1 ):\n", " b = np.array([b]).T\n", " Ab = (np.hstack((A.copy(),b))).astype(float)\n", " else:\n", " Ab = A.copy().astype(float)\n", " \n", " if( traceLevel > 0 and type(b) == type(None)):\n", " print(\"Creating Reduced Row Echelon Form:\\n\")\n", " print(np.round(Ab, decimals=4))\n", " print()\n", " elif( traceLevel > 0 ):\n", " print(\"Running Gaussian Elimination on augmented matrix:\\n\")\n", " print(np.round(Ab, decimals=4))\n", " print()\n", " \n", " B = forwardElimination(Ab,traceLevel)\n", " \n", " if( traceLevel > 0 ):\n", " print(\"Echelon Form:\\n\")\n", " print( np.round(B, decimals=4) + np.zeros(B.shape),\"\\n\") # adding -0.0 + 0 gives 0.0\n", " print()\n", " \n", " if ( type(b) != type(None) and noSolution(B) ):\n", " print(\"No solution!\")\n", "\n", " C = backwardSubstitute(B,type(b)!=type(None),traceLevel)\n", " \n", " if( traceLevel > 0 ):\n", " print(\"Reduced Row Echelon Form:\\n\")\n", " print( np.round(C, decimals=4) + np.zeros(C.shape),\"\\n\") # adding -0.0 + 0 gives 0.0\n", " print()\n", " \n", " return C\n", "\n", "########################################################################################################\n", " \n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 1., 2., 3.],\n", " [ 0., -3., -6.],\n", " [ 0., 0., -9.]])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Using just forward elimination to generate a Row Echelon Form\n", "\n", "A = np.array( [ [1,2,3],[4,5,6],[-3,8,10]])\n", "\n", "forwardElimination(A)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running Forward Elimination on:\n", "\n", "[[ 1. 2. 3.]\n", " [ 4. 5. 6.]\n", " [-3. 8. 10.]] \n", "\n", "\n", "R2 += -4.0*R1\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [-3. 8. 10.]]\n", "\n", "R3 += 3.0*R1\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [ 0. 14. 19.]]\n", "\n", "R3 += 4.6667*R2\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [ 0. 0. -9.]]\n", "\n" ] }, { "data": { "text/plain": [ "array([[ 1., 2., 3.],\n", " [ 0., -3., -6.],\n", " [ 0., 0., -9.]])" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# See all the steps\n", "\n", "forwardElimination(A,2)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 1., 0., 0.],\n", " [ 0., 1., 0.],\n", " [-0., -0., 1.]])" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Just find a RREF\n", "\n", "GaussianElimination(A)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating Reduced Row Echelon Form:\n", "\n", "[[ 1. 2. 3.]\n", " [ 4. 5. 6.]\n", " [-3. 8. 10.]]\n", "\n", "Running Forward Elimination on:\n", "\n", "[[ 1. 2. 3.]\n", " [ 4. 5. 6.]\n", " [-3. 8. 10.]] \n", "\n", "\n", "R2 += -4.0*R1\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [-3. 8. 10.]]\n", "\n", "R3 += 3.0*R1\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [ 0. 14. 19.]]\n", "\n", "R3 += 4.6667*R2\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [ 0. 0. -9.]]\n", "\n", "Echelon Form:\n", "\n", "[[ 1. 2. 3.]\n", " [ 0. -3. -6.]\n", " [ 0. 0. -9.]] \n", "\n", "\n", "Creating Reduced Row Echelon Form...\n", "\n", "R2 = R2/-3.0\n", "\n", "[[ 1. 2. 3.]\n", " [-0. 1. 2.]\n", " [ 0. 0. -9.]]\n", "\n", "R1 += -2.0*R2\n", "\n", "[[ 1. 0. -1.]\n", " [-0. 1. 2.]\n", " [ 0. 0. -9.]]\n", "\n", "R3 = R3/-9.0\n", "\n", "[[ 1. 0. -1.]\n", " [-0. 1. 2.]\n", " [-0. -0. 1.]]\n", "\n", "R1 += 1.0*R3\n", "\n", "[[ 1. 0. 0.]\n", " [-0. 1. 2.]\n", " [-0. -0. 1.]]\n", "\n", "R2 += -2.0*R3\n", "\n", "[[ 1. 0. 0.]\n", " [ 0. 1. 0.]\n", " [-0. -0. 1.]]\n", "\n", "Reduced Row Echelon Form:\n", "\n", "[[1. 0. 0.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]] \n", "\n", "\n" ] }, { "data": { "text/plain": [ "array([[ 1., 0., 0.],\n", " [ 0., 1., 0.],\n", " [-0., -0., 1.]])" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Find a RREF and trace all the stages and row ops\n", "\n", "GaussianElimination(A,traceLevel=2)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No solution!\n" ] }, { "data": { "text/plain": [ "array([[ 1. , 0. , -1. , -2.66666667],\n", " [-0. , 1. , 2. , 2.33333333],\n", " [ 0. , 0. , 0. , -1. ]])" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# if no solution....\n", "\n", "A = np.array( [ [1,2,3],[4,5,6],[7,8,9]])\n", "b = np.array( [[2],[1],[-1]] )\n", "\n", "GaussianElimination(A,b)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running Gaussian Elimination on augmented matrix:\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 4. 5. 6. 1.]\n", " [ 7. 8. 10. -1.]]\n", "\n", "Running Forward Elimination on:\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 4. 5. 6. 1.]\n", " [ 7. 8. 10. -1.]] \n", "\n", "\n", "Echelon Form:\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 0. -3. -6. -7.]\n", " [ 0. 0. 1. -1.]] \n", "\n", "\n", "Creating Reduced Row Echelon Form...\n", "\n", "Reduced Row Echelon Form:\n", "\n", "[[ 1. 0. 0. -3.6667]\n", " [ 0. 1. 0. 4.3333]\n", " [ 0. 0. 1. -1. ]] \n", "\n", "\n" ] }, { "data": { "text/plain": [ "array([[ 1. , 0. , 0. , -3.66666667],\n", " [-0. , 1. , 0. , 4.33333333],\n", " [ 0. , 0. , 1. , -1. ]])" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Tracing the stages of the process \n", "\n", "A = np.array( [ [1,2,3],[4,5,6],[7,8,10]])\n", "b = np.array( [[2],[1],[-1]])\n", "\n", "GaussianElimination(A,b,1)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running Gaussian Elimination on augmented matrix:\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 4. 5. 6. 1.]\n", " [ 7. 8. 10. -1.]]\n", "\n", "Running Forward Elimination on:\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 4. 5. 6. 1.]\n", " [ 7. 8. 10. -1.]] \n", "\n", "\n", "R2 += -4.0*R1\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 0. -3. -6. -7.]\n", " [ 7. 8. 10. -1.]]\n", "\n", "R3 += -7.0*R1\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 0. -3. -6. -7.]\n", " [ 0. -6. -11. -15.]]\n", "\n", "R3 += -2.0*R2\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 0. -3. -6. -7.]\n", " [ 0. 0. 1. -1.]]\n", "\n", "Echelon Form:\n", "\n", "[[ 1. 2. 3. 2.]\n", " [ 0. -3. -6. -7.]\n", " [ 0. 0. 1. -1.]] \n", "\n", "\n", "Creating Reduced Row Echelon Form...\n", "\n", "R2 = R2/-3.0\n", "\n", "[[ 1. 2. 3. 2. ]\n", " [-0. 1. 2. 2.3333]\n", " [ 0. 0. 1. -1. ]]\n", "\n", "R1 += -2.0*R2\n", "\n", "[[ 1. 0. -1. -2.6667]\n", " [-0. 1. 2. 2.3333]\n", " [ 0. 0. 1. -1. ]]\n", "\n", "R1 += 1.0*R3\n", "\n", "[[ 1. 0. 0. -3.6667]\n", " [-0. 1. 2. 2.3333]\n", " [ 0. 0. 1. -1. ]]\n", "\n", "R2 += -2.0*R3\n", "\n", "[[ 1. 0. 0. -3.6667]\n", " [-0. 1. 0. 4.3333]\n", " [ 0. 0. 1. -1. ]]\n", "\n", "Reduced Row Echelon Form:\n", "\n", "[[ 1. 0. 0. -3.6667]\n", " [ 0. 1. 0. 4.3333]\n", " [ 0. 0. 1. -1. ]] \n", "\n", "\n" ] }, { "data": { "text/plain": [ "array([[ 1. , 0. , 0. , -3.66666667],\n", " [-0. , 1. , 0. , 4.33333333],\n", " [ 0. , 0. , 1. , -1. ]])" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Tracing all the row ops\n", "\n", "A = np.array( [ [1,2,3],[4,5,6],[7,8,10]])\n", "b = np.array( [[2],[1],[-1]])\n", "\n", "GaussianElimination(A,b,2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Ok, Your Turn!\n", "\n", "In the following problems, you will analyze a matrix (NOT an augmented matrix) to calculate some useful information\n", "about the matrix.\n", "\n", "Before doing these problems, you should study the Numpy Tutorial posted in the tutorials directory on the class\n", "web site, especially the later sections on Indexing and Slicing, Rearranging Rows and Columns, and Array Stacking. \n", "\n", "## Problem 1\n", "\n", "In this problem, we will take a matrix $A$ and return a tuple consisting of the following information about $A$:\n", "\n", "- The rank of A, i.e., the number of pivots\n", "- A basis for the column space of A \n", "- The nullity of A, i.e., the number of free variables\n", "- A basis for the null space of A\n", "\n", "Examples of what your function should return are given in the following cells. \n", "\n", "Hint: Here are the steps your algorithm should follow:\n", "\n", "- Calculate the RREF form of A; call this B\n", "- Use a double-for loop just as you did in HW 01 to find the pivot positions\n", "- Collect together a list of the columns where pivots occur\n", "- Calculate a list of non-pivot columns\n", "- The basis for Col(A) is the columns in A where pivots occur in B\n", "- The basis for Null(A) is -1 times the columns in B where pivots do NOT occur, with a 1 added at the position of\n", " the corresponding variable \n", "- Rank and nullity can be calculated from the size of the two bases. " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "def analyzeMatrix(A):\n", "\n", " # Your code here\n", " \n", " return (None,None,None,None) # just to get it to compile, replace with your code\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Testing Examples\n", "\n", "To determine if your code is correct, calculate the bases by hand. " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [4 5 6]\n", " [7 8 9]] \n", "\n" ] }, { "data": { "text/plain": [ "(None, None, None, None)" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example (A)\n", "\n", "A = np.array( [ [1,2,3],[4,5,6],[7,8,9]])\n", "print(A,'\\n')\n", "analyzeMatrix(A)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3]\n", " [ 2 4 31]\n", " [ 3 2 10]] \n", "\n" ] }, { "data": { "text/plain": [ "(None, None, None, None)" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example (B)\n", "\n", "A = np.array( [ [1,2,3],[2,4,31],[3,2,10]])\n", "print(A,'\\n')\n", "analyzeMatrix(A)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [2 4 6]\n", " [3 6 9]] \n", "\n" ] }, { "data": { "text/plain": [ "(None, None, None, None)" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example (C)\n", "\n", "A = np.array( [ [1,2,3],[2,4,6],[3,6,9]])\n", "print(A,'\\n')\n", "analyzeMatrix(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem 2\n", "\n", "In this problem, we will take a matrix $A$ and calculate the inverse matrix $A^{-1}$, if it exists; if $A$ has\n", "no inverse, you will return the value `None`. \n", "\n", "You should use the functions defined above, and the method shown on Friday for calculating the inverse\n", "of a square matrix.\n", "\n", "You may use the function `analyzeMatrix` created in the previous problem if you wish. " ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "# If A has no inverse (i.e., is not square or does not have a pivot in every row) then return None,\n", "# else calculate the inverse by horizontally stacking the identity matrix, as shown in lecture on Friday 7/23\n", "\n", "def getInverse(A):\n", "\n", " # Your code here\n", " \n", " return None # just to get it to compile, replace with your code" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A:\n", "[[ 1 2 3]\n", " [-2 4 3]\n", " [ 3 6 -9]] \n", "\n", "Inverse:\n", "None \n", "\n", "\n" ] } ], "source": [ "# Example A\n", "\n", "A = np.array( [ [1,2,3],[-2,4,3],[3,6,-9]])\n", "print(\"A:\")\n", "print(A,'\\n')\n", "Ainv = getInverse(A)\n", "print(\"Inverse:\")\n", "print(Ainv,'\\n')\n", "\n", "# Uncomment these to test your code\n", "\n", "'''\n", "print(\"Test Inverse: A @ Ainv (without rounding) = \")\n", "print(A @ Ainv,'\\n')\n", "print(\"Test Inverse: A @ Ainv (with rounding) = \")\n", "print(np.around(A @ Ainv),'\\n')\n", "print(\"Test Inverse: Ainv @ A (with rounding) = \")\n", "print(np.around(Ainv @ A),'\\n')\n", "print(\"Test Inverse: A @ A @ A @ Ainv @ Ainv @ Ainv (with rounding) = \")\n", "print(np.around(A @ A @ A @ Ainv @ Ainv @ Ainv),'\\n')\n", "'''\n", "print()" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A:\n", "[[ 1 2 3 5 2]\n", " [-2 4 3 8 4]\n", " [ 3 6 -9 1 2]\n", " [ 2 8 3 8 0]\n", " [ 1 16 9 1 -2]] \n", "\n", "Inverse:\n", "None \n", "\n", "\n" ] } ], "source": [ "# Example B\n", "\n", "A = np.array( [ [1,2,3,5,2],[-2,4,3,8,4],[3,6,-9,1,2],[2,8,3,8,0],[1,16,9,1,-2]])\n", "print(\"A:\")\n", "print(A,'\\n')\n", "Ainv = getInverse(A)\n", "print(\"Inverse:\")\n", "print(Ainv,'\\n')\n", "\n", "# Uncomment these to test your code\n", "\n", "'''\n", "print(\"Test Inverse: A @ Ainv (without rounding) = \")\n", "print(A @ Ainv,'\\n')\n", "print(\"Test Inverse: A @ Ainv (with rounding) = \")\n", "print(np.around(A @ Ainv),'\\n')\n", "print(\"Test Inverse: Ainv @ A (with rounding) = \")\n", "print(np.around(Ainv @ A),'\\n')\n", "print(\"Test Inverse: A @ A @ A @ Ainv @ Ainv @ Ainv (with rounding) = \")\n", "print(np.around(A @ A @ A @ Ainv @ Ainv @ Ainv),'\\n')\n", "'''\n", "print()" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A:\n", "[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", " [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]\n", " [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]\n", " [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]\n", " [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n", " [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]\n", " [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]\n", " [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]\n", " [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]\n", " [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]] \n", "\n", "Inverse:\n", "None \n", "\n", "\n" ] } ], "source": [ "# Example C\n", "\n", "A = np.eye(10)\n", "print(\"A:\")\n", "print(A,'\\n')\n", "Ainv = getInverse(A)\n", "print(\"Inverse:\")\n", "print(Ainv,'\\n')\n", "\n", "# Uncomment these to test your code\n", "\n", "'''\n", "print(\"Test Inverse: A @ Ainv (without rounding) = \")\n", "print(A @ Ainv,'\\n')\n", "print(\"Test Inverse: A @ Ainv (with rounding) = \")\n", "print(np.around(A @ Ainv),'\\n')\n", "print(\"Test Inverse: Ainv @ A (with rounding) = \")\n", "print(np.around(Ainv @ A),'\\n')\n", "print(\"Test Inverse: A @ A @ A @ Ainv @ Ainv @ Ainv (with rounding) = \")\n", "print(np.around(A @ A @ A @ Ainv @ Ainv @ Ainv),'\\n')\n", "'''\n", "print()" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A:\n", "[[1 2 3]\n", " [4 5 6]\n", " [7 8 9]] \n", "\n", "Inverse:\n", "None \n", "\n" ] } ], "source": [ "# Example D\n", "\n", "A = np.array( [ [1,2,3],[4,5,6],[7,8,9]])\n", "print(\"A:\")\n", "print(A,'\\n')\n", "Ainv = getInverse(A)\n", "print(\"Inverse:\")\n", "print(Ainv,'\\n') # Should print None\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3\n", "\n", "Solve these problems using Python/numpy. One goal of these problems is to make you more\n", "familiar with using the numpy documentation. It is available at \n", "\n", " http://docs.scipy.org/doc/numpy/reference/index.html. \n", " \n", "Parts of the documentation you will want to read include array creation routines, random\n", "number generation routines, and mathematical functions (for rounding). You should also look over\n", "my `numpy` tutorial on the web site. \n", "\n", "To generate random matrices, you will want to use the `numpy.random` package. (Python has a stand-alone\n", "random library as well, but it will be easier for you if you use routines in numpy.random, so use that library in\n", "your answers below).\n", "\n", "(A) For each case, determine the call to a numpy function that will produce the stated matrix. Show an example in a code cell. \n", "\n", "1. A $5\\times 6$ matrix of all zeros. \n", "\n", "2. A $3\\times 5$ matrix of all ones. \n", "\n", "3. The $6\\times 6$ identity matrix.\n", "\n", "4. A $5\\times 5$ diagonal matrix, with diagonal entries 3, 5, 7, 2, 4. \n", "\n", "(B) Write an expression which will create a $6\\times 4$ matrix containing random floating-point numbers. Show an example in a code cell. \n", "\n", "(C) The expression in (B) created all numbers in the range $[0,1)$; write an expression which would create a random $5\\times 5$ matrix with floating-point numbers in the range $[100,200)$. Show an example in a code cell. \n", "\n" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "# Solution\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 4\n", "\n", "Construct a random $4\\times 4$ matrix and test whether the following equality holds:\n", "\n", "$$(A+I_4)(A-I_4) = (A^2 - I_4).$$\n", "\n", "The best way to do this is to compute the difference between the two sides of the equation\n", "and see if it contains all zeros -- however, you will have to use the function `np.isclose(...)`\n", "because of the problems with floating-point arithmetic. \n", "\n", "\n", "Provide your code, run it, and state whether the equation holds. \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 2 }