torch.polar() Method in Python PyTorch

PyTorchServer Side ProgrammingProgramming

With given absolute values and angles, we can construct a complex number in PyTorch using torch.polar() method. The absolute value and angles must be float or double. Both the absolute value and the angle must be of the same type.

  • If abs is a float, then angle must also be float.

  • If the inputs are torch.float32, then the constructed complex tensor must be torch.complex64.

  • If the inputs are torch.float64, then the complex tensor must be torch.complex128.

Syntax

torch.polar(abs, angle)

Parameters

  • abs – The absolute length of the complex tensor.

  • angle – The angle of the complex tensor.

Steps

We could use the following steps to construct a complex tensor with given abs and angle

  • Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it.

import torch
  • Define two torch tensors − abs and angle. The number of elements in both the tensors must be the same.

abs = torch.tensor([3, 2.5], dtype=torch.float32)
angle = torch.tensor([np.pi / 2, np.pi / 4], dtype=torch.float32)
  • Construct a complex tensor with given abs and angle.

z = torch.polar(abs, angle)
  • Print the computed complex tensor.

print("Complex Number:\n", z)
  • Print the dtype of the complex tensor.

print("dtype of Complex number:",z.dtype)

Example 1

import torch
import numpy as np

# define the absolute value and angle of the complex tensor
abs = torch.tensor([1], dtype=torch.float32)
angle = torch.tensor([np.pi / 4], dtype=torch.float32)

# print absolute value and angle
print("abs:", abs)
print("angle:", angle)
z = torch.polar(abs, angle)
print("Complex number:\n",z)
print("dtype of complex number:\n", z.dtype)

Output

abs: tensor([1.])
angle: tensor([0.7854])
Complex number:
   tensor([0.7071+0.7071j])
dtype of complex number:
   torch.complex64

In the above example, we have constructed a complex tensor of dtype=torch.complex64 with a given absolute length and angle of the tensor.

Example 2

import torch
import numpy as np
abs = torch.tensor([3, 2.5], dtype=torch.float32)
angle = torch.tensor([np.pi / 2, np.pi / 4], dtype=torch.float32)
z = torch.polar(abs, angle)
print(z)

Output

tensor([-1.3113e-07+3.0000j, 1.7678e+00+1.7678j])

Example 3

import torch
import numpy as np
abs = torch.tensor([1.6, 2.3], dtype=torch.float64)
angle = torch.tensor([np.pi / 3, 5 * np.pi / 2], dtype=torch.float64)
z = torch.polar(abs, angle)
print(z)

Output

tensor([8.0000e-01+1.3856j, 7.0417e-16+2.3000j], dtype=torch.complex128)
raja
Updated on 27-Jan-2022 06:03:29

Advertisements