In C++, std::tanh(x) is the hyperbolic tangent. It equals sinh(x) / cosh(x). Its graph is an S-shaped curve that passes through 0 and flattens out at -1 on the left and 1 on the right.
This "squashing" makes it very useful. Whatever number you give it, the answer stays between -1 and 1. That is why it is popular as an activation function in neural networks. Unlike sinh() and cosh(), it never overflows.
std::tanh() is declared in <cmath> and is part of the group Hyperbolic functions. Hyperbolic functions are built from ex. They are not about angles, but they have the same names with an h added.
Syntax
Include <cmath> and call std::tanh. Start with these lines.
C++
double a = std::tanh(0.5); // double version
float b = std::tanh(0.5f); // float version
Call
What it does
std::tanh(0.5)
Passes a double and returns a double. Here the result is 0.462117.
std::tanh(0.5f)
Passes a float, so the float overload runs and returns a float.
std::tanh(1)
An integer is converted to double. Returns 0.761594.
Write std::tanh so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float tanh(float x);
double tanh(double x);
long double tanh(long double x);
double tanh(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. Any number. It is not an angle. An integer is converted to double.
Return Value
Return Value
Description
Hyperbolic tangent
A value from -1 to 1, with the same sign as x.
1 / -1
For large positive or negative x, and for inf and -inf.
0
tanh(0) is exactly 0.
C++ Examples
Example 1 — Hyperbolic Tangent of Common Values
Print tanh() for a few numbers, from zero to a bigger input.
C++
#include <cmath>
#include <iostream>
int main() {
double values[] = {0.0, 0.5, 1.0, 3.0};
for (double v : values) {
std::cout << "tanh(" << v << ") = " << std::tanh(v) << '\n';
}
return 0;
}
weight * input + bias is a straight line, so a big input can give a big sum. The line goes through tanh() next.
The input 0 gives tanh(0.1), which is 0.099668. A negative input gives a negative output, like -0.993927 for -2.
The input 2 gives tanh(3.1), or 0.995873. Whatever the input is, the output stays between -1 and 1.
Frequently Asked Questions
std::tanh(x) returns the hyperbolic tangent of x, which is sinh(x) / cosh(x). The result is always between -1 and 1.
The hyperbolic tangent as float, double, or long double, a value from -1 to 1. tanh(0) is 0, and tanh of a large number is 1.
The result is always between -1 and 1. tanh(0) is 0, and the curve gets closer to 1 and -1 for large numbers but never goes beyond them.
It squashes any number into the range -1 to 1, and it is centered around zero. It is smooth, so it works well when training a network.
Include <cmath> and write std::tanh(). That always works and picks the C++ overloads. The global name ::tanh often works too, but the standard does not promise it, and it may only take a double.