Open In App

Finding Magnitude of a Complex Number in Python

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Complex numbers are an essential part of mathematics and engineering, often encountered in various fields such as signal processing, control systems, and physics. The magnitude of a complex number is a measure of its distance from the origin in the complex plane. In Python, there are several ways to calculate the magnitude of a complex number.

Syntax :

Z= a+jb

Magnitude = √a2 + b2

Finding Magnitude of a Complex Number in Python

Below, are the ways to Finding Magnitude of a Complex Number in Python.

Manually Calculating Magnitude

We can manually calculate the magnitude by taking the square root of the sum of the squares of the real and imaginary parts.

Python3




#Manually calculating magnitude
def magnitude_manual(z):
    return (z.real**2 + z.imag**2)**0.5
 
# Example
complex_number = 3 + 4j
result = magnitude_manual(complex_number)
print(f"Manually calculated magnitude: {result}")


Output

Manually calculated magnitude: 5.0

Magnitude of a Complex Number Using abs() Function

In this example, the abs() function in Python can be used to find the magnitude of a complex number. The abs() function returns the absolute value of a number, and for complex numbers, it calculates the magnitude.

Python3




# Using abs() function
def magnitude_abs(z):
    return abs(z)
 
# Example
complex_number = 3 + 4j
result = magnitude_abs(complex_number)
print(f"Magnitude using abs(): {result}")


Output

Magnitude using abs(): 5.0

Magnitude of a Complex Number Using cmath Module

In this example, the cmath module in Python provides mathematical functions for complex numbers. The cmath module’s abs() function can be used to find the magnitude.

Python3




import cmath
 
#  Using cmath module
def magnitude_cmath(z):
    return cmath.polar(z)[0]
 
# Example
complex_number = 3 + 4j
result = magnitude_cmath(complex_number)
print(f"Magnitude using cmath: {result}")


Output

Magnitude using cmath: 5.0

Magnitude of a Complex Number Using pow() Method

In this example, The math module in Python provides a sqrt() function, which can be combined with the pow() function to find the magnitude.

Python3




import math
 
# Using math module
def magnitude_math(z):
    return math.sqrt(pow(z.real, 2) + pow(z.imag, 2))
 
# Example
complex_number = 3 + 4j
result = magnitude_math(complex_number)
print(f"Magnitude using pow() module: {result}")


Output

Magnitude using pow() module: 5.0

Conclusion

In Conclusion , the above methods offer different ways to calculate the magnitude of a complex number in Python. Choose the one that fits your preference or the requirements of your specific application. Understanding these methods can be beneficial in solving problems related to complex numbers in various scientific and engineering domains.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads