notes

uni notes
git clone git://popovic.xyz/notes.git
Log | Files | Refs

prb5_p.ipynb (1567B)


      1 {
      2  "cells": [
      3   {
      4    "cell_type": "code",
      5    "execution_count": 2,
      6    "id": "a365a539",
      7    "metadata": {},
      8    "outputs": [],
      9    "source": [
     10     "import numpy as np"
     11    ]
     12   },
     13   {
     14    "cell_type": "code",
     15    "execution_count": 3,
     16    "id": "0416380f",
     17    "metadata": {},
     18    "outputs": [],
     19    "source": [
     20     "def damped_richardson(A, b, n, ω):\n",
     21     "    x_k = np.zeros(b.shape[0])\n",
     22     "    for i in range(n):\n",
     23     "        x_k = (np.identity(b.shape[0]) - ω*A)@x_k + ω*b\n",
     24     "    return x_k"
     25    ]
     26   },
     27   {
     28    "cell_type": "code",
     29    "execution_count": 4,
     30    "id": "301ce785",
     31    "metadata": {},
     32    "outputs": [],
     33    "source": [
     34     "A = np.array([[3, 1, 1],\n",
     35     "              [1, 3, 1],\n",
     36     "              [1, 1, 4]])\n",
     37     "b = np.array([2, -4, 3])\n",
     38     "\n",
     39     "# find suitable ω\n",
     40     "λ = np.linalg.eig(A)[0]\n",
     41     "ω = 2/(max(λ) + min(λ))"
     42    ]
     43   },
     44   {
     45    "cell_type": "code",
     46    "execution_count": 5,
     47    "id": "077214f2",
     48    "metadata": {},
     49    "outputs": [],
     50    "source": [
     51     "x = damped_richardson(A, b, 20, ω)\n",
     52     "np.testing.assert_allclose(A@x, b, rtol=1e-5)"
     53    ]
     54   }
     55  ],
     56  "metadata": {
     57   "kernelspec": {
     58    "display_name": "Python 3 (ipykernel)",
     59    "language": "python",
     60    "name": "python3"
     61   },
     62   "language_info": {
     63    "codemirror_mode": {
     64     "name": "ipython",
     65     "version": 3
     66    },
     67    "file_extension": ".py",
     68    "mimetype": "text/x-python",
     69    "name": "python",
     70    "nbconvert_exporter": "python",
     71    "pygments_lexer": "ipython3",
     72    "version": "3.10.4"
     73   }
     74  },
     75  "nbformat": 4,
     76  "nbformat_minor": 5
     77 }