Python math.tanh() 方法返回给定数字的双曲正切值。
双曲正切法,表示为 tanh(x),是一种计算复数或实数 x 的正切值的数学方法。它返回介于 -1 和 1 之间的实际值。
在数学上,双曲正切法定义为 -
tanh(x) = sinh(x)/ cosh(x)
其中,sinh(x) 是双曲正弦法,cosh(x) 是双曲余弦法。这种方法很奇怪,这意味着 tanh(-x) = -tanh(x)。
语法
以下是 Python math.tanh() 方法的基本语法 -
math.tanh(x)
参数
此方法接受要查找双曲正切的数字 (所有实数) 作为参数。
返回值
该方法返回给定数字在 (-1, 1) 范围内的双曲正切值。
示例 1
在下面的示例中,我们使用 math.tanh() 方法计算正数的双曲正切 -
import math
x = 2.0
result = math.tanh(x)
print(result)
输出
获得的输出如下 -
0.9640275800758169
示例 2
如果我们将分数值传递给 math.tanh() 方法,它将返回一个介于 -1 和 1 之间的数字(不包括 -1 和 1)−
import math
from fractions import Fraction
x = Fraction(5, -9)
result = math.tanh(x)
print(result)
输出
以下是上述代码的输出 -
-0.5046723977218567
示例 3
在这里,我们使用 math.tanh() 方法检索负数的双曲正切 -
import math
x = -0.5
result = math.tanh(x)
print(result)
输出
我们得到的输出如下所示 -
-0.46211715726000974
示例 4
在此示例中,我们使用循环通过 math.tanh() 方法计算多个值的双曲正切值。循环遍历值列表中的每个值,计算双曲正切,并打印每个值的结果 -
import math
values = [1.0, 2.0, 3.0]
for x in values:
result = math.tanh(x)
print("tanh({}) = {}".format(x, result))
输出
生成的结果如下所示 -
tanh(1.0) = 0.7615941559557649
tanh(2.0) = 0.9640275800758169
tanh(3.0) = 0.9950547536867305
tanh(2.0) = 0.9640275800758169
tanh(3.0) = 0.9950547536867305