NumPy tanh()

tanh() 函数计算数组中每个元素的双曲正切值。

示例

import numpy as np

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

# calculate the hyperbolic tangent of each value result = np.tanh(values)
print(result) # Output:[-0.96402758 -0.76159416 0. 0.76159416 0.96402758]

tanh() 语法

tanh() 的语法是:

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

tanh() 参数

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

  • x - 输入数组
  • out (可选) - 用于存储结果的输出数组
  • where(可选)- 一个布尔数组或条件,指示在何处计算双曲正切值。
  • dtype (可选) - 输出数组的数据类型

tanh() 返回值

tanh() 方法返回一个数组,其中包含其元素对应的双曲正切值。


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

import numpy as np

values = np.array([-1, 0, 1, 2, 3])

# create an output array of the same shape and data type as 'values', filled with zeros
result = np.zeros_like(values, dtype=float)  

# calculate the hyperbolic tangent where values>=0 and store in result np.tanh(values, out=result, where=(values >= 0))
print(result)

输出

[0.         0.         0.76159416 0.96402758 0.99505475]

这里,

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

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

import numpy as np

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

# calculate the hyperbolic tangent of each value with a specific dtype
tanh_values_float = np.tanh(values, dtype=float)
tanh_values_complex = np.tanh(values, dtype=complex)

print("Hyperbolic tangents with 'float' dtype:")
print(tanh_values_float)

print("\nHyperbolic tangents with 'complex' dtype:")
print(tanh_values_complex)

输出

Hyperbolic tangents with 'float' dtype:
[-0.46211716 -0.19737532  0.          0.19737532  0.46211716]

Hyperbolic tangents with 'complex' dtype:
[-0.46211716+0.j -0.19737532+0.j  0.        +0.j  0.19737532+0.j
  0.46211716+0.j]

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

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

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

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

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