Skip to content

Instantly share code, notes, and snippets.

@DianSano
Created March 8, 2022 08:29
Show Gist options
  • Select an option

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

Select an option

Save DianSano/43d5dc0697bb82c1481875d1a5ce2165 to your computer and use it in GitHub Desktop.
SPL_gauss_jordan.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "SPL_gauss_jordan.ipynb",
"provenance": [],
"authorship_tag": "ABX9TyOWlUir9FlEhypKGF32I3yi",
"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/43d5dc0697bb82c1481875d1a5ce2165/spl_gauss_jordan.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "whqaL78NotM0",
"outputId": "5f36791c-9806-488b-c747-8705f7078fef"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[[1. 1. 1. ]\n",
" [0. 2. 2. ]\n",
" [0. 0. 2.33333333]]\n",
"[4. 6. 2.33333333]\n",
"[[1. 0. 0.]\n",
" [0. 1. 0.]\n",
" [0. 0. 1.]]\n",
"Gauss-Jordan \n",
"The solution of the system is:\n",
"[1. 2. 1.]\n"
]
}
],
"source": [
"from numpy import array, zeros, fabs, linalg\n",
"\n",
"a = array([[1, 1, 1],\n",
" [1, -1, -1],\n",
" [2, 8, 1]], float)\n",
"#the b matrix constant terms of the equations \n",
"b = array([4, -2, 19], float)\n",
"\n",
"n = len(b)\n",
"x = zeros(n, float)\n",
"\n",
"# Forward Elimination\n",
"for k in range(n-1):\n",
" if fabs(a[k,k]) < 1.0e-12:\n",
" # if statements checks if the pivot element is zero\n",
" # and swap it with the appropriate row\n",
" for i in range(k+1, n): \n",
" if fabs(a[i,k]) > fabs(a[k,k]):\n",
" a[[k,i]] = a[[i,k]] # Note a[[0,1]] is not the same to a[0,1]\n",
" b[[k,i]] = b[[i,k]]\n",
" break\n",
"\n",
" for i in range(k+1,n):\n",
" if a[i,k] == 0:continue\n",
"\n",
" factor = a[k,k]/a[i,k]\n",
" for j in range(k,n):\n",
" a[i,j] = a[k,j] - a[i,j]*factor\n",
" #we also calculate the b vector of each row\n",
" b[i] = b[k] - b[i]*factor\n",
"print(a)\n",
"print(b)\n",
"\n",
"# Backward Elimination\n",
"for k in range(n-1,0-1,-1):\n",
" c = a[k,k]\n",
" for i in range(0,k):\n",
" b[i] = b[i] - b[k]*a[i,k]/c\n",
" for j in range(n-1,k-1, -1):\n",
" a[i,j] = a[i,j] - a[k,j]* a[i, k]/c\n",
"\n",
" b[k] = b[k]/c\n",
" a[k,k] /= c\n",
" \n",
"\n",
"print(a)\n",
"print(\"Gauss-Jordan \")\n",
"print(\"The solution of the system is:\")\n",
"print(b)\n"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment