NumPy sin()

The sin() function computes the element-wise sine of an array.

The sine is the trigonometric function that calculates the ratio of the length of the side opposite an angle to the length of the hypotenuse in a right-angled triangle.

Example

import numpy as np

# create an array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# compute the sine of each angle sine_values = np.sin(angles)
# print resulting sine values print(sine_values) # Output: [0. 0.5 0.70710678 0.8660254 1. ]

sin() Syntax

The syntax of sin() is:

numpy.sin(array, out=None, dtype=None)

sin() Arguments

The sin() function takes following arguments:

  • array - the input arrays
  • out (optional) - the output array where the result will be stored
  • dtype (optional) - data type of the output array

sin() Return Value

The sin() function returns an array containing the element-wise sine values of the input array.


Example 1: Compute Sine of the Angles

import numpy as np

# array of angles in radians
angles = np.array([0, 1, 2])
print("Angles:", angles)

# compute the sine of the angles sine_values = np.sin(angles)
print("Sine values:", sine_values)

Output

Angles: [0 1 2]
Sine values: [0.         0.84147098     0.90929743]

In the above example, the sin() function calculates the sine values for each element in the angles array.

The resulting values are in radians.


Example 2: Use out to Store the Result in Desired Location

import numpy as np

# create an array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# create an empty array to store the result
result = np.empty_like(angles)

# compute the sine of angles and store the result in the 'result' array np.sin(angles, out=result)
print("Result:", result)

Output

Result: [0.         0.5        0.70710678 0.8660254  1.        ]

Here, we have used sin() with the out parameter to compute the sine of the angles array and store the result directly in the result array.

The resulting result array contains the computed sine values.


Example 3: Use of dtype Argument in sin()

import numpy as np

# create an array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# compute the sine of angles with different data types sin_float64 = np.sin(angles, dtype=np.float64) sin_float32 = np.sin(angles, dtype=np.float32)
# print the resulting arrays print("Sine values (float64):", sin_float64) print("Sine values (float32):", sin_float32)

Output

Sine values (float64): [0.         0.5        0.70710678 0.8660254  1.        ]
Sine values (float32): [0.         0.5        0.70710677 0.86602545 1.        ]

In the above example, we have the array angles containing five angles in radians.

Here, we used sin() with the dtype argument to compute the sine of the angles with different data types.

Note: The sin() function typically returns floating-point values because the sine function can produce non-integer values for most inputs.