Skip to content

Commit

Permalink
experiment with toeplitz mtxs
Browse files Browse the repository at this point in the history
  • Loading branch information
bogovicj committed Sep 11, 2018
1 parent eb4ac4e commit f423989
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions lecture_1/Lab_1_helpers.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -217,44 +217,60 @@
"source": [
"# Don't ever solve a linear system with an inverse matrix\n",
"* Seriously, you promised\n",
"\n"
"\n",
"The code below solves a linear system in two different ways, first by computing the matrix inverse then multiplying. Then using a smart way `np.linalg.solve`) "
]
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"it took 0.876535177230835 ms the slow way\n",
"it took 0.30843091011047363 ms the fast way\n"
"it took 6.21192193031311 s the slow way\n",
"it took 1.9188358783721924 s the fast way\n",
"are the results different? : False\n"
]
}
],
"source": [
"import time\n",
"\n",
"# Try making it bigger than 2000, if you dare.\n",
"# Try making it bigger than 2000, if you dare \n",
"# (maybe stay under 10k)\n",
"\n",
"medium_mtx = np.array( rng.rand( 2000, 2000 ) )\n",
"medium_vec = np.array( rng.rand( 2000, 1 ) )\n",
"medium_mtx = np.array( rng.rand( 4000, 4000 ) )\n",
"medium_vec = np.array( rng.rand( 4000, 1 ) )\n",
"\n",
"# Solve by computing the matrix inverse, then multiplying\n",
"# See how long it takes\n",
"t0 = time.time()\n",
"slow_result = np.linalg.inv( medium_mtx ) @ medium_vec\n",
"t1 = time.time()\n",
"print( 'it took {} ms the slow way'.format( t1-t0 ))\n",
"print( 'it took {} s the slow way'.format( t1-t0 ))\n",
"\n",
"# Solve in a smart way\n",
"# See how long it takes\n",
"t0_f = time.time()\n",
"fast_result = np.linalg.solve( medium_mtx, medium_vec )\n",
"t1_f = time.time()\n",
"print( 'it took {} ms the fast way'.format( t1_f - t0_f ))\n",
"print( 'it took {} s the fast way'.format( t1_f - t0_f ))\n",
"\n",
"# Check that the results are the same\n",
"# Subtract the results and see if any of the elements are bigger\n",
"( slow_result - fast_result ) > 0.0001"
"# Subtract the results and see if any of the elements are bigger than a tiny number\n",
"print( 'are the results different? : {}'.format( np.any( ( slow_result - fast_result ) > 1e-6 )))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Bonus\n",
"\n",
"Learn about [Toeplitz](https://en.wikipedia.org/wiki/Toeplitz_matrix) matrices. Notices there's a [special way to solve them](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_toeplitz.html#scipy.linalg.solve_toeplitz). Try it - see how the speed compares to solving the random matrix above"
]
},
{
Expand Down

0 comments on commit f423989

Please sign in to comment.