The Wayback Machine - https://web.archive.org/web/20240817152824/https://www.geeksforgeeks.org/gauss-seidel-method/
Open In App

Gauss–Seidel method

Last Updated : 28 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This is to take Jacobi’s Method one step further. Where the better solution is x = (x1, x2, … , xn), if x1(k+1) is a better approximation to the value of x1 than x1(k) is, then it would better that we have found the new value x1(k+1) to use it (rather than the old value that isx1(k)) in finding x2(k+1), … , xn(k+1). So x1(k+1) is found as in Jacobi’s Method, but in finding x2(k+1), instead of using the old value of x1(k) and old values of x3(k),…, xn(k), we then use the new value x1(k+1) and the old values x3(k), … , xn(k), and similarly for finding x3(k+1), … , xn(k+1). This process to find the solution of the given linear equation is called the

Gauss-Seidel Method

The Gauss–Seidel method is an iterative technique for solving a square system of n (n=3) linear equations with unknown x. Given

Ax=B

, to find the system of equation x which satisfy this condition. In more detail, A, x and b in their components are :

Then the decomposition of A Matrix into its lower triangular component and its upper triangular component is given by:

The system of linear equations are rewritten as:

The Gauss–Seidel method now solves the left hand side of this expression for x, using previous value for x on the right hand side. More formally, this may be written as:

However, by triangular form of L*, the elements of x(k+1) can be computed sequentially using forward substitution:

This process is continuously repeated until we found the better approximated solution with least error.

Examples:

Input :
3
4x+ y+ 2z= 4
3x+ 5y+ 1z= 7
x+ y+ 3z= 3

Output :
[0, 0, 0]
[1.0, 0.8, 0.39999999999999997]
[0.6000000000000001, 0.9599999999999997, 0.48000000000000004]
[0.52, 0.9919999999999998, 0.49600000000000005]
[0.504, 0.9983999999999998, 0.4992000000000001]
[0.5008, 0.99968, 0.49984]
[0.5001599999999999, 0.9999360000000002, 0.4999679999999999]
[0.500032, 0.9999872, 0.4999936]
[0.5000064, 0.9999974400000001, 0.49999871999999995]
[0.50000128, 0.999999488, 0.4999997439999999]
[0.500000256, 0.9999998976000001, 0.49999994880000004]
[0.5000000512, 0.9999999795199999, 0.4999999897600001]
[0.50000001024, 0.999999995904, 0.499999997952]
[0.500000002048, 0.9999999991808, 0.49999999959040003]
[0.5000000004095999, 0.9999999998361601, 0.49999999991808003]
[0.50000000008192, 0.9999999999672321, 0.49999999998361594]
[0.500000000016384, 0.9999999999934465, 0.49999999999672307]
[0.5000000000032768, 0.9999999999986894, 0.4999999999993445]
[0.5000000000006554, 0.9999999999997378, 0.49999999999986894]
[0.500000000000131, 0.9999999999999478, 0.49999999999997374]
[0.5000000000000262, 0.9999999999999897, 0.49999999999999467]
[0.5000000000000052, 0.9999999999999979, 0.49999999999999895]
[0.5000000000000011, 0.9999999999999994, 0.49999999999999983]
[0.5000000000000002, 0.9999999999999998, 0.5000000000000001]
[0.49999999999999994, 1.0, 0.5]
[0.5, 1.0, 0.5]

Given the three equation:

4x + y + 2z = 4
3x + 5y + z = 7
x + y + 3z = 3

First we assume that the solution of given equation is

(0,0,0)

Then first we put value of y and z in equation 1 and get value of x and update the value of x as

(x1,0,0)

Now, putting the updated value of x that is x1 and z=0 in equation 2 to get y1 and then updating our solution as

(x1,y1,0)

Then, at last putting x1 and y1 in equation 3 to get z1 and updating our solution as

(x1,y1,z1)

Now repeat the same process 24 more times to get the approximate solution with minimum error.

Python3




# Defining our function as seidel which takes 3 arguments
# as A matrix, Solution and B matrix
  
def seidel(a, x ,b):
    #Finding length of a(3)      
    n = len(a)                  
    # for loop for 3 times as to calculate x, y , z
    for j in range(0, n):       
        # temp variable d to store b[j]
        d = b[j]                 
         
        # to calculate respective xi, yi, zi
        for i in range(0, n):    
            if(j != i):
                d-=a[j][i] * x[i]
        # updating the value of our solution       
        x[j] = d / a[j][j]
    # returning our updated solution          
    return x   
  
# int(input())input as number of variable to be solved               
n = 3                             
a = []                           
b = []       
# initial solution depending on n(here n=3)                    
x = [0, 0, 0]                       
a = [[4, 1, 2],[3, 5, 1],[1, 1, 3]]
b = [4,7,3]
print(x)
 
#loop run for m times depending on m the error value
for i in range(0, 25):           
    x = seidel(a, x, b)
    #print each time the updated solution
    print(x)                    


An example for the matrix version A linear system shown as Ax=b is given by:

We want to use the equation

Where:

We must decompose A into the sum of a lower triangular component L* and a strict upper triangular component U:

The Inverse of L* is:

Now we can find remaining things:

Now we have T and C and we can use them to obtain the vectors x iteratively. First of all, we have to choose x{0} we can only guess. The better the guess, the quicker the algorithm will perform. We suppose:

Then we can iteratively calculate other x{i’s}:

Now we know the Exact solution which matches the answer calculated above.

In fact, the matrix A is strictly diagonally dominant (but not positive definite).



Previous Article
Next Article

Similar Reads

Python | Using variable outside and inside the class and method
In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let's see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable na
3 min read
Python - os.pardir() method with example
In Python, OS module provides various functions to interact with the operating system. This module comes under the Python standard utility module, so there is no need to install it manually. os.pardir is a constant string used by the operating system to refer to the parent directory. This method is also available via os.path.pardir() Note: os.pardi
1 min read
Python: os.path.abspath() method with example
OS module in Python provides various methods for interacting with the operating system. It comes under Python's standard utility module, so there is no need to install it externally. os.path is a submodule of OS module which contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used f
2 min read
Python OpenCV - cv2.polylines() method
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and it now plays a major role in real-time operations which are very important in today’s systems. By using OpenCV one can process images and videos to identify objects, faces, or even the handwriting of a human. When it is combined with various libra
3 min read
Python program to convert any base to decimal by using int() method
Given a number and its base, the task is to convert the given number into its corresponding decimal number. The base of number can be anything like digits between 0 to 9 and A to Z. Where the value of A is 10, value of B is 11, value of C is 12 and so on. Examples: Input : '1011' base = 2 Output : 11 Input : '1A' base = 16 Output : 26 Input : '1234
2 min read
Python Tuple - index() Method
While working with tuples many times we need to access elements at a certain index but for that, we need to know where exactly is that element, and here comes the use of the index() function. In this article, we will learn about the index() function used for tuples in Python. Example : The Index() method returns the first occurrence of the given el
2 min read
Python Tuple - max() Method
While working with tuples many times we need to find the maximum element in the tuple, and for this, we can also use max(). In this article, we will learn about the max() method used for tuples in Python. Example Tuple =( 4, 2, 5, 6, 7, 5) Input: max(Tuple) Output: 7 Explanation: The max() method returns the largest element of the given tuple. Pyth
2 min read
Python Tuple - len() Method
While working with tuples many times we need to find the length of the tuple, and, instead of counting the number of elements with loops, we can also use Python len(). We will learn about the len() method used for tuples in Python. Example: C/C++ Code Tuple =( 1, 0, 4, 2, 5, 6, 7, 5) print(len(Tuple)) Output : 8Python tuple len() Method SyntaxSynta
2 min read
Python Tuple count() Method
In this article, we will learn about the count() method used for tuples in Python. The count() method of a Tuple returns the number of times the given element appears in the tuple. Example C/C++ Code tuple = (1, 2, 3, 1, 2, 3, 1, 2, 3) print(tuple.count(3)) Output : 3Python Tuple count() Method Syntax Syntax: tuple.count( ele ) Parameters: ele: Any
3 min read
Fibonacci Series Program In Python Using Iterative Method
Fibonacci series is a series where each number is the sum of its two previous numbers. In this article, we are going to generate Fibonacci series in Python using Iterative methods. We will be covering both the loops i.e. for loop and while loop. In this article, we will be covering all the concepts related to the topic with clear and concise exampl
4 min read
How to Call a Method on a Class Without Instantiating it in Python?
In Python programming, classes and methods are like building blocks for organizing our code and making it efficient. Usually, we create instances of classes to access their parts—attributes and methods. But sometimes, we might want to use a class or its methods without actually creating an instance. In this article, we'll dive into four different w
3 min read
Python Super() With __Init__() Method
In object-oriented programming, inheritance plays a crucial role in creating a hierarchy of classes. Python, being an object-oriented language, provides a built-in function called super() that allows a child class to refer to its parent class. When it comes to initializing instances of classes, the __init__() method is often used. Combining super()
4 min read
How to Use __call__() Method Instead of __new__() of a Metaclass in Python?
In Python, metaclasses provide a way to customize class creation. The __new__ and __init__ methods are commonly used in metaclasses, but there's another powerful tool at your disposal: the __call__ method. While __new__ is responsible for creating a new instance of a class, __call__ allows you to control what happens when an instance is called as a
3 min read
Python | Difference between two dates (in minutes) using datetime.timedelta() method
To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two DateTime objects. To find the difference between two dates in the form of minutes, the attribute seconds of timedelta object can be used which can be further divided by 6
2 min read
Python Programs
Python Examples: Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python code examples cover a wide range o
13 min read
How to Fix: PermissionError: [Errno 13] Permission Denied in Python
When your Python code encounters a situation where it lacks the necessary permissions to access a file or directory, it raises PermissionError: [Errno 13] Permission denied in Python. This article will explore how to address the Errno 13 Error in Python effectively. What is PermissionError: [Errno 13] Permission Denied in Python?PermissionError: [E
5 min read
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python provides us with a number of in-built data structures such as lists, tuples, sets, and dictionaries that are used to store and organize the data in an efficient manner. In this article, we will learn the difference between them and their applications. Python ListPython Lists are just like dynamic-sized arrays, declared in other languages (ve
7 min read
Defaultdict in Python
Dictionary in Python is an unordered collection of data values that are used to store data values like a map. Unlike other Data Types that hold only single value as an element, the Dictionary holds key-value pair. In Dictionary, the key must be unique and immutable. This means that a Python Tuple can be a key whereas a Python List can not. A Dictio
5 min read
Python | Split string into list of characters
Given a string, write a Python program to split the characters of the given string into a list using Python. In this article, we will explore various methods to split a string into a list of characters, allowing developers to manipulate and work with individual characters efficiently. Input: geeksOutput : ['g', 'e', 'e', 'k', 's']Input: WordOutput
4 min read
Python | Get dictionary keys as a list
Given a dictionary, write a Python program to get the dictionary keys as a list. Examples: Input : {1:'a', 2:'b', 3:'c'}Output : [1, 2, 3]Input : {'A' : 'ant', 'B' : 'ball'}Output : ['A', 'B']Method 1: Get dictionary keys as a list using dict.keys()Python list() function takes any iterable as a parameter and returns a list. In Python, iterable is t
5 min read
Python Program to Convert a List to String
Given a list, write a Python program to convert the given list to a string. There are various situations we might encounter when a list is given and we convert it to a string in Python. For example, conversion to a string from a list of strings or a list of integers. Example Input: ['Geeks', 'for', 'Geeks']Output: Geeks for GeeksExplanation: The In
7 min read
Python program to interchange first and last elements in a list
Given a list, write a Python program to swap first and last element of the list. Examples: Input : [12, 35, 9, 56, 24] Output : [24, 35, 9, 56, 12] Input : [1, 2, 3] Output : [3, 2, 1] Approach #1: Find the length of the list and simply swap the first element with (n-1)th element. [GFGTABS] Python # Python3 program to swap first # and last element
6 min read
Python Program to Swap Two Elements in a List
Given a list in Python and provided the positions of the elements, write a program to swap the two elements in the list. Examples: Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3Output : [19, 65, 23, 90] Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5Output : [1, 5, 3, 4, 2] Swap Two Elements in a List using comma assignment Since the positi
4 min read
Python Program to Print all Prime numbers in an Interval
Given two positive integers start and end. The task is to write a Python program to print all Prime numbers in an Interval. Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}. Table of Content Python Program for Prime NumberOptimiz
7 min read
How to Add Two Numbers in Python - Easy Programs
Learn easy techniques and codes to add numbers in Python. Adding numbers in Python is a very easy task, and we have provided you 7 different ways to add numbers in Python. Given two numbers num1 and num2. The task is to write a Python program to find the addition of these two numbers. Examples: Input: num1 = 5, num2 = 3Output: 8Input: num1 = 13, nu
6 min read
Python Program to Check Prime Number
Given a positive integer N, the task is to write a Python program to check if the number is Prime or not in Python. Examples: Input: n = 11Output: TrueInput: n = 1Output: FalseExplanation: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}. Py
7 min read
How to print without newline in Python?
Generally, people switching from C/C++ to Python wonder how to print two or more variables or statements without going into a new line in python. Since the Python print() function by default ends with a newline. Python has a predefined format if you use print(a_variable) then it will go to the next line automatically. Example Input: [geeks,geeksfor
5 min read
Python Program to Find the Factorial of a Number
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Find the Factorial of a Number Using Recursive approachThis Python program uses a recursive function to calculate the factorial of a given number. The factorial is computed by multiplying the num
4 min read
Python Program for Binary Search (Recursive and Iterative)
In a nutshell, this search algorithm takes advantage of a collection of elements that is already sorted by ignoring half of the elements after just one comparison. Compare x with the middle element.If x matches with the middle element, we return the mid index.Else if x is greater than the mid element, then x can only lie in the right (greater) half
4 min read
Python Program to Print the Fibonacci sequence
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation. Fn = Fn-1 + Fn-2 with seed values : F0 = 0 and F1 = 1. Fibonacci Numbers using Native ApproachFibonacci series using a Pyth
3 min read
Article Tags :
three90RightbarBannerImg