C++ std::tanh
In C++, std::tanh returns the hyperbolic tangent of x. For finite real inputs the mathematical result lies between −1 and 1, approaching either limit for large magnitudes.
A simple example
std::tanh
- Start with 0
- Do this Evaluate at the origin
- Result 0
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::tanh(0.0)) << '\n';
}
0
Syntax
std::tanh(signal)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonSmooth a strong sensor signal
A sensor signal grows much larger than its usual range. Transform the reading into a bounded response so a display or model can still distinguish ordinary changes.
#include <cmath>
#include <cstdio>
int main() {
const double signal = 2.0;
std::printf("%.3f\n", std::tanh(signal));
return 0;
}
0.964
A signal of two maps to about 0.964. Stronger inputs approach one gradually.
Keep a joystick centred
A controller smooths its signed input using hyperbolic tangent. Its calibration test begins with the joystick exactly centred.
Using 0 gives 0.000 for this measurement.
Smooth a leftward input
A game controller maps signed input to a bounded motion signal. The player moves the stick left and the raw input reaches minus one.
Using -1 gives -0.762 for this measurement.
What to watch for
Scaling the input changes how quickly the output approaches its limit.