Library contents

C tanh

In C, 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

tanh

  1. Start with 0
  2. Do this Evaluate at the origin
  3. Result 0
At zero the positive and negative exponential terms are equal. Their difference is zero.
lesson.c
#include <stdio.h>
#include <math.h>

int main(void) {
    printf("%.15g\n", (double) (tanh(0.0)));
}
Output
0

Syntax

C syntax
tanh(signal)
Run these examples in C

Save one example at a time as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Smooth 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.

From the programdouble signal = 2.0
Result0.964
lesson.c
#include <math.h>
#include <stdio.h>

int main(void) {
    double signal = 2.0;

    printf("%.3f\n", tanh(signal));
    return 0;
}
Output
0.964

A signal of two maps to about 0.964. Stronger inputs approach one gradually.

Advertisements

Keep a joystick centred

A controller smooths its signed input using hyperbolic tangent. Its calibration test begins with the joystick exactly centred.

Given0
Worked result0.000

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.

Given-1
Worked result-0.762

Using -1 gives -0.762 for this measurement.

What to watch for

Scaling the input changes how quickly the output approaches its limit.

Documentation for tanh