NumPy arctan2()

numpy.arctan2() 方法计算 y / x 的逐元素反正切(反正切),其中 yx 是数组。

示例

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() 方法返回一个与 yx 形状相同的数组,其中包含 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 的元素,yx 相除的逐元素反正切。

并且通过设置 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

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战