NumPy arccos()

arccos() 方法计算数组中每个元素的反余弦(余弦的逆)。

示例

import numpy as np

# create an array of values between -1 and 1
values = np.array([-1, -0.5, 0, 0.5, 1])

# calculate the inverse cosine of each value inverseCosines = np.arccos(values)
print(inverseCosines) # Output: [3.14159265 2.0943951 1.57079633 1.04719755 0. ]

arccos() 语法

arccos() 的语法是:

numpy.arccos(x, out = None, where = True, dtype = None)

arccos() 参数

arccos() 方法接受以下参数:

  • x - 输入数组
  • out (可选) - 用于存储结果的输出数组
  • where (可选) - 一个布尔数组或条件,指示在哪里计算反余弦。
  • dtype (可选) - 输出数组的数据类型

arccos() 返回值

arccos() 方法返回一个包含相应反余弦值的数组。


示例 1:在 arccos() 中使用 out 和 where

import numpy as np

# create an array of values between -0.5 and 0.5
values = np.array([-0.5, -0.2, 0, 0.2, 0.5])

# create an array of zeros with the same shape as values
result = np.zeros_like(values, dtype = float)  

# calculate inverse cosine where values >= 0 and store in result. np.arccos(values, out = result, where = (values >= 0))
print(result)

输出

[0.         0.         1.57079633 1.36943841 1.04719755]

这里,

  • out = result 指定 np.arccos() 函数的输出应存储在 result 数组中。
  • where=(values >= 0) 指定反余弦运算仅应用于 values 中大于或等于 0 的元素。

示例 2:在 arccos() 中使用 dtype 参数

import numpy as np

# create an array of values
values = np.array([0, 1, -1])

# calculate the inverse cosine of each value with float data type arccos Float = np.arccos(values, dtype = float)
print("Inverse Cosine with 'float' dtype:") print(arccos Float)
# calculate the inverse cosine of each value with complex data type arccosComplex = np.arccos(values, dtype = complex)
print("\nInverse Cosine with 'complex' dtype:") print(arccosComplex)

输出

Inverse Cosine with 'float' dtype:
[1.57079633 0.         3.14159265]

Inverse Cosine with 'complex' dtype:
[1.57079633-0.j 0.        -0.j 3.14159265-0.j]

在这里,通过指定所需的 dtype,我们可以根据特定需求控制输出数组的数据类型。

注意:要了解有关 dtype 参数的更多信息,请访问 NumPy 数据类型

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

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

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