numpy.arctan2()
方法计算 y / x
的逐元素反正切(反正切),其中 y
和 x
是数组。
示例
import numpy as np
# create arrays for y and x coordinates
y = np.array([1, -1, 1, -1])
x = np.array([1, 1, -1, -1])
# compute the element-wise arc tangent of y / x
result = np.arctan2(y, x)
# print the resulting angles
print(result)
# Output: [ 0.78539816 -0.78539816 2.35619449 -2.35619449]
arctan2() 语法
numpy.arctan2()
方法的语法是:
numpy.arctan2(y, x, out = None, where = True, order = 'K', dtype = None)
arctan2() 参数
numpy.arctan2()
方法接受以下参数:
y
- 包含 y 坐标值的数组x
- 包含 x 坐标值的数组out
(可选) - 用于存储结果的输出数组where
(可选) - 一个布尔数组或条件,用于指定应更新哪些元素order
(可选) - 指定输出数组的顺序dtype
(可选) - 返回输出的数据类型
arctan2() 返回值
numpy.arctan2()
方法返回一个与 y 和 x 形状相同的数组,其中包含 y / x
的逐元素反正切。
示例 1:arctan2() 中的可选 out 和 where 参数
import numpy as np
# create arrays for y and x coordinates
y = np.array([1, -1, 1, -1])
x = np.array([1, 1, -1, -1])
# create a condition array
condition = np.array([True, False, True, False])
# create an array of zeros with the same shape as y, using float data type
result = np.zeros_like(y, dtype = float)
# compute the element-wise arc tangent
# of y / x, using the provided condition
# and store the result in the result array
np.arctan2(y, x, out = result, where = condition)
# print the resulting angles
print(result)
输出
[0.78539816 0. 2.35619449 0. ]
在上面的示例中,arctan2()
计算 condition 数组中相应值为 True
的元素,y
与 x
相除的逐元素反正切。
并且通过设置 out = result
,将输出存储在 result 数组中。
示例 2:arctan2() 中 dtype 参数的使用
import numpy as np
# create arrays for y and x coordinates
y = np.array([2.5, -3.8, 1.2, -4.6])
x = np.array([-1.5, 2.7, -3.1, 0.9])
# compute arctan2 with float32 dtype
resultFloat = np.arctan2(y, x, dtype = np.float32)
# compute arctan2 with float64 dtype
resultDouble = np.arctan2(y, x, dtype = np.float64)
# print results
print("Result with float32 dtype:")
print(resultFloat)
print("\nResult with float64 dtype:")
print(resultDouble)
输出
Result with float32 dtype: [ 2.1112158 -0.9530406 2.772259 -1.3775848] Result with float64 dtype: [ 2.11121583 -0.9530406 2.772259 -1.37758484]
通过指定不同的 dtype
值,我们可以控制结果数组的精度和内存使用情况。
在此示例中,resultFloat 的数据类型为 float32
,而 resultDouble 的数据类型为 float64
。