tan()
函数计算数组中元素的正切值。正切是三角函数,用于计算直角三角形中与某个角相对的边长与相邻边长之比。
示例
import numpy as np
# array of angles in radians
angles = np.array([0, 1, 4])
# compute the tangent of the angles
result = np.tan(angles)
print(result)
# Output : [0. 1.55740772 1.15782128]
tan() 语法
tan()
的语法是:
numpy.tan(array, out = None, dtype = None)
tan() 参数
tan()
函数接受以下参数:
array
- 输入数组out
(可选) - 用于存储结果的输出数组dtype
(可选) - 输出数组的数据类型
tan() 返回值
tan()
函数返回一个包含输入数组的每个元素反正切值的数组。
示例 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 tangent of the angles
tangent_values = np.tan(angles)
print("tangent values:", tangent_values)
输出
Angles: [0. 0.78539816 1.57079633 3.14159265] tangent values: [ 0.00000000e+00 1.00000000e+00 1.63312394e+16 -1.22464680e-16]
在此示例中,我们有一个名为 angles 的数组,其中包含四个弧度制的角度:0、π/4、π/2 和 π。
np.tan()
函数用于计算 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 tangent of angles and store the result in the 'result' array
np.tan(angles, out=result)
print("Result:", result)
输出
Result: [1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17]
在这里,我们使用带有 out
参数的 tan()
来计算 angles 数组的正切值,并将结果直接存储在 result 数组中。
result 数组包含计算出的正切值。
示例 3:在 tan() 中使用 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 tangent of each angle with a specific dtype
tangents_float = np.tan(angles, dtype=float)
tangents_complex = np.tan(angles, dtype=complex)
print("Tangents with 'float' dtype:")
print(tangents_float)
print("\nTangents with 'complex' dtype:")
print(tangents_complex)
输出
Tangents with 'float' dtype: [ 0.00000000e+00 1.00000000e+00 1.63312394e+16 -1.22464680e-16] Tangents with 'complex' dtype: [ 0.00000000e+00+0.j 1.00000000e+00+0.j 1.63312394e+16+0.j -1.22464680e-16+0.j]
通过指定所需的 dtype
,我们可以根据我们的要求指定输出数组的数据类型。
注意:要了解有关 dtype
参数的更多信息,请访问 NumPy 数据类型。