How to compute the sine of elements of a tensor in PyTorch?

To compute the sine of elements of a tensor, we use the torch.sin() method. It returns a new tensor with the sine values of the elements of the original input tensor. This function is element-wise and preserves the original tensor's shape.

Syntax

torch.sin(input, out=None) ? Tensor

Parameters

  • input ? Input tensor containing elements in radians
  • out ? Optional output tensor to store the result

Example 1: 1D Tensor

Computing sine values for a one-dimensional tensor ?

import torch

# Create a 1D tensor
T = torch.tensor([1.3, 4.32, 4.4, 5.3, 4.5])
print("Original Tensor T:")
print(T)

# Compute the sine of tensor elements
sine_T = torch.sin(T)
print("\nSine values:")
print(sine_T)
Original Tensor T:
tensor([1.3000, 4.3200, 4.4000, 5.3000, 4.5000])

Sine values:
tensor([ 0.9636, -0.9240, -0.9516, -0.8323, -0.9775])

Example 2: 2D Tensor

Computing sine values for a multi-dimensional tensor ?

import torch

# Create a 2D tensor of size 3x5
T = torch.tensor([[1.3, 4.32, 4.4, 5.3, 4.5],
                  [0.2, 0.3, 0.5, 0.7, 0.9],
                  [1.1, 1.2, 2.3, 3.1, 4.9]])
print("Original Tensor T:")
print(T)

# Compute the sine of tensor elements
sine_T = torch.sin(T)
print("\nSine values:")
print(sine_T)
Original Tensor T:
tensor([[1.3000, 4.3200, 4.4000, 5.3000, 4.5000],
        [0.2000, 0.3000, 0.5000, 0.7000, 0.9000],
        [1.1000, 1.2000, 2.3000, 3.1000, 4.9000]])

Sine values:
tensor([[ 0.9636, -0.9240, -0.9516, -0.8323, -0.9775],
        [ 0.1987,  0.2955,  0.4794,  0.6442,  0.7833],
        [ 0.8912,  0.9320,  0.7457,  0.0416, -0.9825]])

Example 3: Using Common Angles

Working with common trigonometric angles ?

import torch
import math

# Create tensor with common angles in radians
angles = torch.tensor([0, math.pi/6, math.pi/4, math.pi/3, math.pi/2])
print("Angles (in radians):")
print(angles)

# Compute sine values
sine_values = torch.sin(angles)
print("\nSine values:")
print(sine_values)

# Round for cleaner display
print("\nRounded sine values:")
print(torch.round(sine_values, decimals=4))
Angles (in radians):
tensor([0.0000, 0.5236, 0.7854, 1.0472, 1.5708])

Sine values:
tensor([0.0000, 0.5000, 0.7071, 0.8660, 1.0000])

Rounded sine values:
tensor([0.0000, 0.5000, 0.7071, 0.8660, 1.0000])

Key Points

  • The function operates element-wise on the input tensor
  • Input values should be in radians, not degrees
  • The output tensor has the same shape as the input tensor
  • The original tensor remains unchanged (creates a new tensor)

Conclusion

The torch.sin() function provides an efficient way to compute sine values for tensor elements. It preserves tensor shape and operates element-wise, making it ideal for mathematical operations in deep learning workflows.

Updated on: 2026-03-26T18:44:36+05:30

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements