What is numpy.cos() in Python?
The numpy.cos() method in Python calculates the ratio of the length of the side nearest to the angle to the length of the hypotenuse. This function returns the cosine of a number. To be more precise, it returns the cosine of a radian.
A visual representation of the cosine () is as follows.
Syntax
numpy.cos(x, out=None)
Input parameters
x: This method takes an array of radian numbers as an input.out=None: This is an optional parameter in thenumpy.cos()function. This could bendarray,None, ortupleof thendarray. This parameter identifies a location where the solution or output is stored.
Returns
This method returns an ndarray containing the cosine values of radian numbers from the input. The output may be scalar if the input is scalar.
Example
import numpy as np# Creating an arrayarray = np.array([0, np.pi/2, np.pi])#Calculating the cosine of the valuesresult = np.cos(array)#Using the out parameternew_result = np.array([0, np.pi/2, np.pi])np.cos(array, out = new_result)print("Cosine of values : ", result)print("New Result array : ", new_result)
Explanation
- Line 3: We create an array using the
np.array()method. - Line 6: We calculate the cosine of the values in the
array. - Line 9: We create a new array in this statement.
- Line 10: We calculate the cosine values and store them in the
new_resultarray using theoutparameter.
Note: Providing the
outparameter in thenumpy.cos()function will store the result in theoutparameter, and return a reference to it.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved