2022/04/20

Pi (π) in Torch Tensor - torch.pi

There is no pi (π) function in PyTorch with some version, so some people suggested to use math.pi or np.pi for conversion into torch tensor. For me, torch.pi works with a notebook without the GPU, but not with a computer with the GPU.

Here is the code to compare different implementations of the Pi function.

import torch

import numpy as np

import time

import math


#test pi

time_start = time.perf_counter()

pi_math = torch.tensor(math.pi)

time_elapsed_test = (time.perf_counter() - time_start)

print('math pi time =',time_elapsed_test)


time_start = time.perf_counter()

pi_np = torch.tensor(np.pi)

time_elapsed_test = (time.perf_counter() - time_start)

print('np pi time =',time_elapsed_test)


time_start = time.perf_counter()

pi_torch = torch.pi

time_elapsed_test = (time.perf_counter() - time_start)

print('torch pi time =',time_elapsed_test)


time_start = time.perf_counter()

PI = torch.acos(torch.Tensor([-1]))

time_elapsed_test = (time.perf_counter() - time_start)

print('PI time =',time_elapsed_test)


Results for computation time:

math pi time = 3.6502000057225814e-05

np pi time = 1.9006000002264045e-05

torch pi time = 8.009999419300584e-07

PI time = 0.00035780000007434865


Hence torch.pi is the fastest.


Without torch.pi, you may use torch.tensor(np.pi)

For an accurate pi, cast the type to float64:

torch.tensor(np.pi, dtype=torch.float64)

Example:

(Pdb) torch.tensor(np.pi)*100000

tensor(314159.2812)

(Pdb) torch.tensor(np.pi, dtype=torch.float64)*100000

tensor(314159.2654, dtype=torch.float64)

MATLAB:

pi = 3.141592653589793

Reference:

Np.pi equivalent in Pytorch

Is there the Pi greek (3.1415…) defined somewhere?