Skip to content

Instantly share code, notes, and snippets.

@DianSano
Last active March 8, 2022 08:39
Show Gist options
  • Select an option

  • Save DianSano/a594e0998ed30bf8fad81c5353a3ceee to your computer and use it in GitHub Desktop.

Select an option

Save DianSano/a594e0998ed30bf8fad81c5353a3ceee to your computer and use it in GitHub Desktop.
SPL_gauss_seidel.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "SPL_gauss_seidel.ipynb",
"provenance": [],
"authorship_tag": "ABX9TyMsSxEjKigU2NZA/xTl5Z0G",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/DianSano/a594e0998ed30bf8fad81c5353a3ceee/spl_gauss_seidel.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "TaFS0Ue5qEEw",
"outputId": "25d3c3dc-36c1-4a30-8772-0f76b5313840"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[[ 4. -1. 1.]\n",
" [-1. 4. -2.]\n",
" [ 1. -2. 4.]]\n",
"[12. -1. 5.]\n",
"[3. 1. 1.]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"a = np.array([[4, -1, 1],\n",
" [-1, 4, -2],\n",
" [1, -2, 4]], float)\n",
"#the b matrix constant terms of the equations \n",
"b = np.array([12, -1, 5], float)\n",
"\n",
"def gauss_seidel(A, b, tolerance=1e-10, max_iterations=10000):\n",
" \n",
" x = np.zeros_like(b, dtype=np.double)\n",
" \n",
" #Iterate\n",
" for k in range(max_iterations):\n",
" \n",
" x_old = x.copy()\n",
" \n",
" #Loop over rows\n",
" for i in range(A.shape[0]):\n",
" x[i] = (b[i] - np.dot(A[i,:i], x[:i]) - np.dot(A[i,(i+1):], x_old[(i+1):])) / A[i ,i]\n",
" \n",
" #Stop condition \n",
" if np.linalg.norm(x - x_old) / np.linalg.norm(x) < tolerance:\n",
" break\n",
" \n",
" return x\n",
"\n",
"print(a)\n",
"print(b)\n",
"x = gauss_seidel(a, b)\n",
"print(x)\n"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment