PyTorch torch.polar() method is “used to construct a complex number using absolute value and angle.” The data types of these absolute values and angles must float or double.
Syntax
torch.polar(abs, angle)
Parameters
- abs (Tensor): The tensor containing magnitudes (absolute values) for the complex numbers.
- angle (Tensor): The tensor containing phases (angles in radians) for the complex numbers.
Example 1: Use of a torch.polar()
import torch
# Define magnitude and phase tensors
magnitudes = torch.tensor([1.0, 2.0, 3.0])
phases = torch.tensor([0.0, 3.141592653589793/2, 3.141592653589793])
# Construct complex tensor using polar
complex_tensor = torch.polar(magnitudes, phases)
print("Complex Tensor:")
print(complex_tensor)
Output
Complex Tensor:
tensor([ 1.0000e+00+0.0000e+00j, -8.7423e-08+2.0000e+00j,
-3.0000e+00-2.6227e-07j])
You can see that the resulting complex tensor will have values corresponding to the complex numbers with the provided magnitudes and phases.
Example 2: Using Random Values
import torch
magnitudes_random = torch.rand(5)
phases_random = torch.rand(5) * 2 * 3.141592653589793
# Construct complex tensor using polar
complex_tensor_random = torch.polar(magnitudes_random, phases_random)
print("Random Magnitudes:")
print(magnitudes_random)
print("\nRandom Phases:")
print(phases_random)
print("\nComplex Tensor from Random Values:")
print(complex_tensor_random)
Output
Example 3: Reconstructing Complex Numbers
import torch
# Create a complex tensor
complex_tensor_original = torch.tensor([1+2j, 3+4j, -2-3j],
dtype=torch.complex64)
# Extract magnitudes and phases
magnitudes_extracted = torch.abs(complex_tensor_original)
phases_extracted = torch.angle(complex_tensor_original)
# Reconstruct complex tensor using polar
complex_tensor_reconstructed = torch.polar(magnitudes_extracted,
phases_extracted)
print("Original Complex Tensor:")
print(complex_tensor_original)
print("\nExtracted Magnitudes:")
print(magnitudes_extracted)
print("\nExtracted Phases:")
print(phases_extracted)
print("\nReconstructed Complex Tensor:")
print(complex_tensor_reconstructed)
Output
That’s it!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.