cos()
函数计算数组中元素的余弦值。
余弦是三角函数,用于计算直角三角形中一个角度的邻边长度与斜边长度之比。
示例
import numpy as np
# array of angles in radians
angles = np.array([0, 1, 5])
# compute the cosine of the angles
cosineValues = np.cos(angles)
print(cosineValues)
# Output : [1. 0.54030231 0.28366219]
cos() 语法
cos()
的语法如下:
numpy.cos(array, out = None, dtype = None)
cos() 参数
cos()
函数接受以下参数:
array
- 输入数组out
(可选) - 用于存储结果的输出数组dtype
(可选) - 输出数组的数据类型
cos() 返回值
cos()
函数返回一个数组,其中包含输入数组中每个元素的余弦值。
示例 1:计算角度的余弦值
import numpy as np
# array of angles in radians
angles = np.array([0, np.pi/4, np.pi/2, np.pi])
print("Angles:", angles)
# compute the cosine of the angles
cosineValues = np.cos(angles)
print("cosine values:", cosineValues)
输出
Angles: [0. 0.78539816 1.57079633 3.14159265] cosine values: [ 1.00000000e+00 7.07106781e-01 6.12323400e-17 -1.00000000e+00]
在此示例中,我们有一个名为 angles 的数组,其中包含四个弧度角的角度:0、π/4、π/2 和 π。
np.cos()
函数用于计算 angles 数组中每个元素的余弦值。
示例 2:使用 out 将结果存储在所需位置
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 cosine of angles and store the result in the 'result' array
np.cos(angles, out=result)
print("Result:", result)
输出
Result: [1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17]
在这里,我们使用带有 out
参数的 cos()
来计算 angles 数组的余弦值,并将结果直接存储在 result 数组中。
生成的 result 数组包含计算出的余弦值。
示例 3:在 cos() 中使用 dtype 参数
import numpy as np
# create an array of angles in radians
angles = np.array([0, np.pi/4, np.pi/2, np.pi])
# calculate the cosine of each angle with a specific dtype
floatCosines = np.cos(angles, dtype=float)
complexCosines = np.cos(angles, dtype=complex)
print("Cosines with 'float' dtype:")
print(floatCosines)
print("\nCosines with 'complex' dtype:")
print(complexCosines)
输出
Cosines with 'float' dtype: [ 1.00000000e+00 7.07106781e-01 6.12323400e-17 -1.00000000e+00] Cosines with 'complex' dtype: [ 1.00000000e+00-0.j 7.07106781e-01-0.j 6.12323400e-17-0.j -1.00000000e+00-0.j]
在这里,通过指定所需的 dtype
,我们可以根据特定需求控制输出数组的数据类型。
注意:要了解有关 dtype
参数的更多信息,请访问 NumPy 数据类型。