{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Coding Back-Substitution" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's an upper-triangular matrix $A$ and two vectors $x$ and $b$ so that $Ax=b$.\n", "\n", "See if you can find $x$ by computation." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0.53359808 -1.66129881 0.31267643 -0.07384466 1.20957795]\n", " [-0. -1.1204435 -1.5348203 1.38270361 -0.34971611]\n", " [ 0. 0. -0.47187693 0.9763103 0.55054242]\n", " [ 0. -0. -0. -0.16929913 0.21209806]\n", " [-0. 0. 0. -0. -0.52165269]]\n", "[-0.9170418 1.40215838 1.41534372 -0.53305575 -1.02625922]\n" ] } ], "source": [ "n = 5\n", "\n", "A = np.random.randn(n, n) * np.tri(n).T\n", "print(A)\n", "\n", "x = np.random.randn(n)\n", "print(x)\n", "\n", "b = A @ x" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "xcomp = np.zeros(n)\n", "\n", "for i in range(n-1, -1, -1):\n", " tmp = b[i]\n", " for j in range(n-1, i, -1):\n", " tmp -= xcomp[j]*A[i,j]\n", " \n", " xcomp[i] = tmp/A[i,i]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now compare the computed $x$ against the reference solution." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.9170418 1.40215838 1.41534372 -0.53305575 -1.02625922]\n", "[-0.9170418 1.40215838 1.41534372 -0.53305575 -1.02625922]\n" ] } ], "source": [ "print(x)\n", "print(xcomp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions/comments:\n", "\n", "* Can this fail?\n", "* What's the operation count?" ] } ], "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.5.1+" } }, "nbformat": 4, "nbformat_minor": 0 }