Namespaces
Variants

std:: tanh (std::valarray)

From cppreference.net
定义于头文件 <valarray>
template < class T >
valarray < T > tanh ( const valarray < T > & va ) ;

对于 va 中的每个元素,计算该元素值的双曲正切函数。

目录

参数

va - 要应用操作的值数组

返回值

包含 va 中值的双曲正切函数值的数组。

注释

使用未限定的函数( tanh )执行计算。若该函数不可用,由于 实参依赖查找 机制,将使用 std:: tanh

该函数可以实现为返回类型不同于 std::valarray 的情况。此时,替换类型需具备以下特性:

可能的实现

template<class T>
valarray<T> tanh(const valarray<T>& va)
{
    valarray<T> other = va;
    for (T& i : other)
        i = tanh(i);
    return other; // 可能返回代理对象
}

示例

#include <cmath>
#include <iostream>
#include <valarray>
auto show = [](char const* title, const std::valarray<double>& va)
{
    std::cout << title << " :";
    for (auto x : va)
        std::cout << "  " << std::fixed << x;
    std::cout << '\n';
};
int main()
{
    const std::valarray<double> x = {.0, .1, .2, .3};
    const std::valarray<double> sinh = std::sinh(x);
    const std::valarray<double> cosh = std::cosh(x);
    const std::valarray<double> tanh = std::tanh(x);
    const std::valarray<double> tanh_by_def = sinh / cosh;
    const std::valarray<double> tanh_2x = std::tanh(2.0 * x);
    const std::valarray<double> tanh_2x_by_def = 
        (2.0 * tanh) / (1.0 + std::pow(tanh, 2.0));
    show("x              ", x);
    show("tanh(x)        ", tanh);
    show("tanh(x) (def)  ", tanh_by_def);
    show("tanh(2*x)      ", tanh_2x);
    show("tanh(2*x) (def)", tanh_2x_by_def);
}

输出:

x               :  0.000000  0.100000  0.200000  0.300000
tanh(x)         :  0.000000  0.099668  0.197375  0.291313
tanh(x) (def)   :  0.000000  0.099668  0.197375  0.291313
tanh(2*x)       :  0.000000  0.197375  0.379949  0.537050
tanh(2*x) (def) :  0.000000  0.197375  0.379949  0.537050

参见

对 valarray 的每个元素应用函数 std::sinh
(函数模板)
对 valarray 的每个元素应用函数 std::cosh
(函数模板)
(C++11) (C++11)
计算双曲正切函数 ( tanh(x) )
(函数)
计算复数的双曲正切函数 ( tanh(z) )
(函数模板)