What is Python complex() Function?

Python complex() is a built-in function used to create a complex number. A complex number comprises both a real part and an imaginary part. You represent it in the form a + bj, where a is the real part and b is the imaginary part.

Whenever you encounter situations that involve working with complex numbers, especially in scientific or engineering applications where you need both real and imaginary components, the complex() function will be very helpful. It allows you to perform various mathematical operations involving complex numbers with ease.

To develop a comprehensive understanding of Python complex() function and conveniently work with its intriguing examples, it is essential to start by exploring its syntax, parameters, and return value. This examination will provide you with a clear grasp of the function’s functionality and characteristics, allowing you to easily harness its capabilities for your programming needs.

Python complex() Syntax and Parameters

The syntax for Python complex() is very simple:

complex(real, imag)

When working with the Python complex() function, you have the flexibility to provide two parameters. These parameters include real and imag which you can utilize as needed. Now, let’s delve deeper into each of these parameters to gain a better understanding.

I. Real

In the complex() function, you can use this parameter to specify the real part of the complex number. It is flexible, allowing you to input either an integer or a float value.

II. Imag

In the complex() function, you can use this parameter to define the imaginary part of the complex number. It accepts both integers and floats, and you can represent it by suffixing the value with ‘j‘ to indicate the imaginary unit.

To sum up, these are the syntax and parameters you can employ in your Python code when utilizing the complex() function. Now, let’s explore the function’s return value to understand how it works in real-life scenarios.

Python complex() Return Value

When you use the complex() function in Python, it returns a complex number object that represents the combination of the given real and imaginary parts. This complex number object is a special data type in Python used to handle complex numbers, which consist of a real part and an imaginary part. Let’s take a look at an example to understand the return value of the complex() function:

Example Code
z = complex(3, 5) print("Complex representation of 3 and 5 is: ",z)

In this example, we created a complex number z with a real part of 3 and an imaginary part of 5. The complex() function returns the complex number object on the screen.

Output
Complex representation of 3 and 5 is: (3+5j)

As you can see, the complex() function allows you to easily obtain the complex representation of any integer value. This flexibility enables you to work with complex numbers in Python seamlessly.

What does complex() do in Python?

Python complex() function is designed to construct and create complex number objects. These objects are a core part of Python numeric data types and are used to handle mathematical operations involving complex numbers.

A complex number in Python is represented in the form (real + imagj), where real is the real part (an integer or a float) and imag is the imaginary part (an integer or a float, suffixed with 'j'). The complex() function combines these two parts to create a complex number object. Let’s examine some examples to better grasp the functionality of the Python complex() function.

I. Python complex() Object Creation

When you call Python complex() with appropriate real and imaginary parts, it internally constructs a complex number object that stores these values. This object allows you to perform various mathematical operations. Now, let’s consider an example:

Example Code
num1=2 num2=4 numbers = complex(2, 4) print("The complex representation of ",num1," and ",num2," is: ",numbers)

For this example, we have two variables, num1 and num2, where we’ve assigned the values 2 and 4, respectively. We then use the Python complex() function to create a complex number. By passing 2 as the real part and 4 as the imaginary part to the function, we obtain a complex number representation. We store this result in the variable numbers.

To display the complex representation along with the given values, we use a print() statement. It will output the message “The complex representation of “, followed by the values of num1 and num2, and then ” is: “, followed by the complex number stored in the variable numbers. The format of the complex number will be “(real + imaginaryj)”.

Output
The complex representation of 2 and 4 is: (2+4j)

This illustrates the complex representation of num1 and num2 as a single complex number using the complex() function.

II. Creating complex numbers with complex()

In the earlier examples, you witnessed the creation of complex numbers using the complex() function. Now, you can notice that it can also be utilized with negative integer values, resulting in their complex number representations. You have the option to pass both real and imaginary parts as arguments or utilize variables to represent these components. Now, let’s examine an example to illustrate its usage:

Example Code
a = 2 b = -4 z = complex(a, b) print("Complex representation of ",a," and ",b, " is: ",z)

Here, we have defined two variables, a and b, where a is assigned the value 2 and b is assigned the value -4. We then utilize the Python complex() function to create a complex number. By passing a as the real part (which is 2) and b as the imaginary part (which is -4), we obtain a complex number representation. We store this result in the variable z.

To display the complex representation along with the given values, we use a print() statement. The output will show “Complex representation of “, followed by the value stored in a, then ” and “, followed by the value stored in b, and finally ” is: “, followed by the complex number stored in the variable z. The format of the complex number will be “(real + imaginaryj)”

Output
Complex representation of 2 and -4 is: (2-4j)

The above example showcases that the complex representation of a and b as a single complex number using the complex() function, even when b has a negative value.

III. Creating Complex Number without complex()

You can utilize Python complex() to easily create complex numbers by directly specifying the real and imaginary parts. However, there are alternative ways for you to construct complex numbers without explicitly using the complex() function. One such method involves using mathematical expressions to combine real and imaginary parts. For example:

Example Code
real_part = 2 imag_part = -3 z = real_part + imag_part * 1j print(z)

In this example, we created the complex number z by combining the real part 2 with the imaginary part -3, using the imaginary unit 1j.

Output
(2-3j)

The example provided above shows that you have an alternative approach to create complex numbers in Python without using the complex() function.

Converting Other Data Types Using complex()

Python complex() function is not limited to your creation of complex numbers from real and imaginary parts alone. It extends its capability to enable conversion from various other data types to complex numbers. Let’s explore a few scenarios that will help you grasp how integers, floats, and strings can be converted into complex numbers.

I. Converting Integers to Complex Number

Converting integers to a complex number in Python involves creating a complex number with the integer value as the real part and the imaginary part set to 0. The resulting complex number will be in the form (integer + 0j), where integer represents the integer value you want to convert. This process allows you to work with complex numbers in mathematical operations even when you start with a simple integer.  Now, let’s explore an example to illustrate this concept:

Example Code
integer_value = 5 complex_number = complex(integer_value) print("Complex representation of", integer_value, "is:", complex_number)

For this example, we convert the integer 5 to a complex number using the complex() function. The resulting complex number is (5+0j) since the imaginary part is set to 0. This process enables you to perform operations with complex numbers even when you start with an integer value.

Output
Complex representation of 5 is: (5+0j)

By using this approach, you can easily convert an integer value into its complex representation.

II. Converting Float to Complex Number

Converting a float to a complex number in Python entails generating a complex number with the float value as the real part and 0 as the imaginary part. The outcome will be a complex number represented in the format (float + 0j), with the float value being the original floating-point number you intend to convert. For example:

Example Code
x=1.5 y=2.7 z3 = complex(1.5, 2.7) print("Complex representation of ",x," and ",y," is: ",z3)

Here ,we have two variables x and y, where we’ve assigned the floating-point values 1.5 and 2.7, respectively. We utilize the Python complex() function to create a complex number z3 with 1.5 as the real part (representing x) and 2.7 as the imaginary part (representing y). The resulting complex number is in the format (1.5 + 2.7j). When we execute the code and use the print() statement, it displays the output on the screen.

Output
Complex representation of 1.5 and 2.7 is: (1.5+2.7j)

As evident from the output above, you have the option to utilize floating-point numbers with the complex() function to convert them into their corresponding complex representations.

III. Converting Strings to Complex Number

You can also convert strings representing complex numbers to complex number objects using the complex() function. let’s explore an example:

Example Code
num_string = "7-2j" z_string = complex(num_string) print("The string ",num_string," into complex number is: ",z_string)

For this example, we encounter a variable num_string holding the string value “7-2j.” As we utilize the complex() function, we convert this string into a complex number. The complex() function can handle strings in a specific format to create the complex number representation. In the string “7-2j,” the “7” is considered the real part, while the “-2j” denotes the imaginary part with “-2” as its value.

Subsequently, when we execute the code and apply the print() statement, it displays “The string,” followed by the value stored in num_string, and then ” into complex number is:”, followed by the complex number stored in the variable z_string.

Output
The string 7-2j into complex number is: (7-2j)

This illustrates how the complex() function can convert a string with the appropriate format into its corresponding complex representation.

Python complex() and Non-Primitive Datatypes

Python complex() can also work with non-primitive data types, such as lists, tuples, set and dictionaries. By extracting appropriate values from these data types, you can create complex numbers as needed. Let’s examine the utilization of complex() with different datatypes.

I. Python complex() with List

When you use Python complex() function with a list as an argument, it attempts to create a complex number from the elements of the list. The list must contain two elements, where the first element is considered as the real part, and the second element is considered as the imaginary part. If the list contains more than two elements, or if the elements are not valid numeric values, it will raise a TypeError. Here’s an example to illustrate this:

Example Code
my_list = [3, 4] z = complex(my_list[0], my_list[1]) print("Complex representation of the list is:", z)

Here, we create a list my_list with two elements [3, 4], and then we use the complex() function to create a complex number from the elements of the list. The first element 3 becomes the real part, and the second element 4 becomes the imaginary part. The resulting complex number is prints on the screen by using print() function.

Output
Complex representation of the list is: (3+4j)

By observing the example provided above, you gain insight into using a list with the complex() function in your Python programs

II. Python complex() with Tuples

In Python, if you utilize the complex() function with a tuple as input, it functions similarly to when you use a list. The tuple should consist of two elements, with the first element representing the real part and the second element representing the imaginary part. By doing so, the function generates a complex number using these elements. Nonetheless, if the tuple contains more than two elements or if the elements are not valid numeric values, it will raise a TypeError. An illustrative example of using the complex() function with a tuple is provided below:

Example Code
my_tuple = (5, -2) number = complex(my_tuple[0], my_tuple[1]) print("Complex representation of the tuple is:", number)

In this example, we create a tuple my_tuple with two elements (5, -2), and then we use the complex() function to create a complex number from the elements of the tuple. The first element 5 becomes the real part, and the second element -2 becomes the imaginary part. The resulting complex number is (5-2j).

Output
Complex representation of the tuple is: (5-2j)

This illustrates the straightforward approach of working with tuples to create complex numbers in your Python code.

III. Python complex() with Sets

When using Python complex() function with a set as an argument, it will raise a TypeError. The complex() function expects either two numeric arguments (real and imaginary parts) or a single string argument that represents a complex number. Since sets are unordered collections of unique elements and don’t have a fixed position, it doesn’t provide the appropriate format for creating complex numbers using the complex() function.

Here’s an example to illustrate using the complex() function with a set, which will result in a TypeError:

Example Code
# Using the complex() function with a set my_set = {3, 4} z = complex(my_set) print("Complex representation of the set is:", z)

Here, we are attempting to use the complex() function with a set as the argument. The set, denoted as my_set, contains the elements 3 and 4. However, when we try to create a complex number using complex(my_set), it results in a TypeError. The reason is that the complex() function requires either two numeric arguments (representing the real and imaginary parts) or a single string argument that represents a complex number. Since sets are unordered collections and don’t preserve the position of elements, they do not fulfill the requirements for creating complex numbers using the complex() function. Consequently, the code will raise a TypeError when executed.

Output
TypeError: complex() argument must be a string or a number, not ‘set’

As shown in the output, using the complex() function with a set raises a TypeError due to the incompatible data type.

IV. Python complex() with Dictionary

You can use Python complex() with a dictionary as an argument but it will raise a TypeError. The complex() function expects either two numeric arguments (real and imaginary parts) or a single string argument that represents a complex number. Since dictionaries are unordered collections of key-value pairs and do not have a specific ordering for the keys and values, they do not provide the appropriate format for creating complex numbers using the complex() function.

Here’s an example to illustrate using the complex() function with a dictionary, which will result in a TypeError:

Example Code
my_dict = {'real': 3, 'imaginary': 4} z = complex(my_dict) print("Complex representation of the dictionary is:", z)

For this example, we are attempting to use the complex() function with a dictionary as the argument. The dictionary, denoted as my_dict, contains key-value pairs where the key ‘real‘ maps to the value 3, and the key ‘imaginary‘ maps to the value 4. However, when we try to create a complex number using complex(my_dict), it results in a TypeError. The reason is that the complex() function expects either two numeric arguments (representing the real and imaginary parts) or a single string argument that represents a complex number. Since a dictionary is not in the appropriate format to directly create a complex number, the code will raise a TypeError when executed.

Output
TypeError: complex() argument must be a string or a number, not ‘dict’

As shown in the output, using the complex() function with a dictionary raises a TypeError due to the incompatible data type.

Python complex() Advanced Examples

In the sections ahead, we will explore advanced examples of the Python complex() function, showcasing its extensive applications. These examples will underscore the diverse and flexible nature of complex() and illustrate how it can be effectively utilized to address a wide range of programming scenarios in Python.

I. Difference Between complex() and real Function

In Python, you will find that the complex() function and the real function serve distinct purposes when it comes to handling complex numbers. Let’s explore an example that will help you grasp the distinction between the complex() function and the real function.

A. complex() Function

You can use the complex() function to create complex number objects in Python by explicitly specifying the real and imaginary parts. This function requires two arguments: the real part and the imaginary part, both of which can be integers, floats, or variables representing numerical values. Once the complex number object is created, you can perform various operations involving complex numbers with it. Here’s an example to illustrate:

Example Code
def create_complex(real, imag): return complex(real, imag) x = 90 y = 12 z = create_complex(x, y) print(z)

Here, we define a function create_complex() that takes two arguments, real and imag, representing the real and imaginary parts of the complex number, respectively. Inside the function, we use the complex() function to create the complex number and return it.

By calling the create_complex() function with appropriate real and imaginary values, we create a complex number and store it in the variable z. The print statement displays the complex representation of the values x and y.

Output
Complex representation of 90 and 12 is: (90+12j)

As you can see, by using this above approach with the create_complex() function, you can easily generate the complex representation of the values 90 and 12, resulting in the complex number

B. real Function

In Python, you can utilize the real function as an attribute of a complex number object to extract the real part of the complex number. When working with complex numbers, this function is helpful to access the real component. You can directly use the real function on a complex number object without requiring any arguments. Here’s an example to illustrate:

Example Code
def extract_real(complex_num): return complex_num.real # Example usage z = complex(0, 41) real_part = extract_real(z) print("The real part of the complex number", z, "is:", real_part)

In this example, we define a function extract_real() that takes a complex number complex_num as an argument. Inside the function, we use the real attribute of the complex number to extract its real part and return it. By calling the extract_real() function with a complex number z, we extract its real part and store it in the variable real_part. The print statement displays the real part of the complex number z on the screen.

Output
The real part of the complex number 41j is: 0.0

Through the method shown above, you can readily compute the real part of any complex number with ease.

In summary, the complex() function is used to create complex number objects, while the real function is used to extract the real part of a complex number.

II. Performing Arithmetic Operations with Complex Numbers

Python’s support for complex numbers makes it easy to perform arithmetic operations involving complex numbers. You can use standard arithmetic operators like addition, subtraction, multiplication, and division to work with complex numbers. To provide a clear illustration of this concept, let’s delve into an example:

Example Code
z1 = complex(20, 16) z2 = complex(-1, 49) # Addition result_add = z1 + z2 print("Addition:", result_add) # Subtraction result_sub = z1 - z2 print("Subtraction:", result_sub) # Multiplication result_mul = z1 * z2 print("Multiplication:", result_mul) # Division result_div = z1 / z2 print("Division:", result_div)

Here, we as programmers, have two complex numbers, z1 and z2, which we create using the complex() function. z1 is assigned the value of complex number (20+16j), and z2 is assigned the value of complex number (-1+49j).  To showcase different operations involving complex numbers, we conduct addition, subtraction, multiplication, and division operations between these two complex numbers.

For addition, we use the + operator to add z1 and z2, and the result is stored in the variable result_add. Similarly, we employ the - operator for subtraction, the * operator for multiplication, and the / operator for division. The results of each operation are stored in the respective variables result_sub, result_mul, and result_div.

Finally, we use print() statements to display the results of each operation. When executed, the output will show the results of addition, subtraction, multiplication, and division of the complex numbers z1 and z2.

Output
Addition: (19+65j)
Subtraction: (21-33j)
Multiplication: (-804+964j)
Division: (0.3180682764363031-0.414654454621149j)

This showcases Python’s capability to handle complex number arithmetic with simplicity and flexibility.

III. Handling Errors and Exceptions with complex()

When you work with complex numbers, it becomes crucial to handle potential errors and exceptions that may occur during operations. One common situation involves mathematical operations that can lead to inconsistencies or the generation of invalid complex numbers. Let’s consider an example where dividing by zero may result in an exception:

Example Code
z1 = complex(4, 5) z2 = complex(0, 0) try: result = z1 / z2 print("Result:", result) except ZeroDivisionError: print("Error: Division by zero is not allowed.")

For this example, we attempted to divide complex number z1 by z2, where z2 has both real and imaginary parts set to zero. This operation would result in a division by zero, which is not allowed in Python. To handle this potential error, we used a try-except block to catch the ZeroDivisionError and provide a helpful error message.

Output
Error: Division by zero is not allowed.

In the above example, you can also manage error exceptions in complex() functions by implementing try and except blocks in your code.

Now that you have acquired a comprehensive understanding of Python complex(), its usage, and its flexibility in various scenarios, you possess a strong foundation. However, to deepen your understanding, let’s explore some theoretical concepts that will be immensely valuable in your Python programming journey.

Python complex() Practical Use Cases

Throughout this article, you have explored the flexibility and functionality of Python’s complex() function. Now, let’s summarize some practical use cases and examples where you can witness the effectiveness of the complex() function:

I. Engineering and Physics Simulations

Complex numbers are prevalent in engineering and physics simulations, especially when dealing with AC circuits, signal processing, and electromagnetic fields. The complex() function allows engineers and physicists to model and analyze these complex systems efficiently.

II. Digital Signal Processing

In digital signal processing, you often encounter situations where complex numbers are employed to represent signals containing both amplitude and phase information. When working in such scenarios, the complex() function becomes a valuable tool, as it facilitates the effortless creation and manipulation of these complex signals in your Python programs.

III. Control Systems Analysis

In control systems, including those used in robotics or automation, you will frequently encounter complex numbers during the analysis of system stability and behavior. In such cases, the complex() function plays a crucial role, providing valuable support and functionality for conducting these analyses easily in your Python code.

IV. Fourier Transforms

In your Python projects, you will find that complex numbers play a vital role in Fourier transforms, which are essential in various domains such as signal processing, image analysis, and other data transformation applications. They enable you to easily handle complex data representations, allowing for more advanced and accurate processing of signals and images.

V. Numerical Computations

When dealing with numerical computations that involve complex mathematical expressions, the complex() function provides a straightforward way to represent complex numbers.

Use of complex() in Mathematical and Scientific Applications

In your mathematical and scientific endeavors, the complex() function proves to be an essential tool. It empowers you, as a mathematician, scientist, or engineer, to handle complex numbers easily, facilitating more accurate and sophisticated computations in your Python programs. This capability enhances the precision and effectiveness of various mathematical and scientific applications you may encounter.

In your Python coding, the complex() function serves as an amazing tool in various mathematical and scientific applications. For mathematical tasks, you can utilize it to solve complex algebraic equations, analyze roots of complex polynomials, and conduct complex analysis in number theory. In scientific contexts, the complex() function plays a key role in fields like electrical engineering for AC circuit analysis, quantum mechanics, and quantum computing. It is also invaluable in signal processing applications for audio and image analysis, as well as in simulations related to fluid dynamics and wave propagation. Embracing the complex() function allows you to tackle these complex tasks with ease and precision.

Considerations and Limitations with complex()

As you work with complex numbers, it’s important to be mindful of certain considerations and limitations that come with their usage:

I. Imaginary Unit

Remember, when dealing with complex numbers in Python, it’s important to note that the imaginary unit is represented by ‘j‘ rather than ‘i,’ as seen in some other mathematical notations.

II. Precision

As you engage in numerical computations with complex numbers, it’s crucial to be aware of possible precision issues. Keep in mind the potential for rounding errors and floating-point inaccuracies that can affect your calculations.

III. Division by Zero

Be cautious when performing division operations with complex numbers, as dividing by zero can lead to exceptions. Always handle potential errors with proper error handling.

IV. Domain-Specific Knowledge

For complex mathematical analyses, it’s crucial to have a solid understanding of the underlying domain and mathematical principles. Mistakes in complex computations can lead to inaccurate results.

Congratulations!, you’ve fully learned the Python complex() function. Throughout this Python Helper guide you have learned how to create complex numbers, which have both real and imaginary parts. How to represent them in the form “a + bj,” where “a” is the real part and “b” is the imaginary part. How to convert integers, floats, and even strings into complex numbers and using Python complex() with Lists Tuples Sets and Dictionaries.

Remember, you can provide two parameters, “real” and “imag,” to the complex() function. The “real” parameter represents the real part of the complex number and can be an integer or a float, while the “imag” parameter represents the imaginary part, also accepting integers or floats with a “j” suffix.

While working with complex numbers, always keep in mind the “j” notation for the imaginary unit in Python, and be mindful of precision issues that may arise due to rounding errors and floating-point inaccuracies.

So, congratulations on your journey with Python complex() function! Enhance its usage, and you’ll excel in various mathematical and scientific applications. Remember, practice and understanding the domain-specific knowledge are essential to mastering complex computations. Keep exploring, coding, and pushing your boundaries as you continue your Python programming adventure! Happy coding!

 
Scroll to Top