What is Complex Number in Python

  • Complex number is one of the built-in datatypes of Python. Even though most are aware that such datatype exists in Python, few may have used this in real-time situations. This topic covers the basics of complex number datatype, details on the real and imaginary part of complex numbers and know when we require to use complex numbers.

  • Complex Number Basics

    A complex number is an element that has 2 parts. Real and imaginary. In a number system complex numbers are represented in the format a + bi. Here a is the real part and bi is the imaginary part.

    Now the question is what is an imaginary number.

    To answer this, let us consider the square root of a number. Lets say √9.
    We all know the answer is 3.

    But what is the result of √-9.
    We cannot find the square root of a negative number.

    This is where the usage of imaginary numbers comes. Using imaginary numbers we can express the square root of negative numbers. We have seen earlier that an imaginary part is represented as bi, where i = √-1

    Let us consider the below sample for better understanding.

    Consider √-9
    
    There is a mathematical rule that, we can represent √ab as √a*√b
    
    Applying this rule
    
    	√-9 = √9*√-1
    	    = 3*i
    	    = 3i
    

    So the √-9 can be represented as an imaginary number 3i.
    And, real number + imaginary number = complex number

    Now, what is the use of an imaginary number?

    You might remember about studying about polynomials in your school days. These are expressions consisting to variables and coefficients.
    Example: (a + b)^2 = a^2 + 2ab + b^2

    We may be able to use real numbers only to solve many of these kind of expressions. But, there are also many expressions, which are unsolvable using real numbers alone. This is where complex numbers comes into play and allows solutions to all such polynomial equations.

  • Complex Number Usages in Python

    In Python, complex number is represented in the format, a + bj.

    We can use j or J in the imaginary part. But no other letters are allowed.

    Python being a language most used in AI, data science and analytics, support for complex numbers is a must. These above said polynomial equations are used everywhere for Artificial Intelligence and Data Science implementations and complex numbers becomes an integral part of it.

  • Basic Operations on Complex Numbers

    Python supports all the basic operations on complex numbers.

    To create a complex number

    num = complex(5, 10)
    Output: 5+10j

    To extract real and imaginary part

    num = 5+10j
    print(num.real, num.imag)
    Output: 5.0, 10.0

    Addition

    print(3+2j + 5+5j)
    Output: 8+7j

    Subtraction

    print((8+2j) - (5+5j))
    Output: (3-3j)

    Multiplication

    print((8+2j) * (5+5j))
    Output: (30+50j)

    Division

    print((1+4j) / (2+2j))
    Output: (1.25+0.75j)

Absolute Code Works - Python Topics