math.tanh(x) computes the hyperbolic tangent (sinh(x) / cosh(x)), smoothly mapping any real number into the interval [-1.0, 1.0].
Because both numerator and denominator grow at the same rate for huge |x|, math.tanh() never raises OverflowErrorβit saturates cleanly at 1.0 and -1.0.
math.tanh() is a function in Python's standard math module: import it with import math and call math.tanh(...), or import the name directly with from math import tanh.
Zero-centered output. Unlike sigmoid which runs from 0 to 1, math.tanh() centers cleanly at 0.0000.
Odd symmetry. Opposing inputs -1.0 and +1.0 map to equal magnitudes -0.7616 and +0.7616.
Smooth saturation. By z = 3.0, the curve is already over 99.5% of the way to one.
Example 2 — Model Skydiver Speed Approaching Terminal Velocity
Evaluate quadratic drag speed v_term * math.tanh(g * t / v_term) over drop time.
python
import math
v_term = 50.0
g = 10.0
for t in [0, 2, 5, 10, 30]:
speed = v_term * math.tanh(g * t / v_term)
print(f"t={t:>2}s -> speed={speed:>5.2f} m/s")
Output
t= 0s -> speed= 0.00 m/s
t= 2s -> speed=19.00 m/s
t= 5s -> speed=38.08 m/s
t=10s -> speed=48.20 m/s
t=30s -> speed=50.00 m/s
How It Works
Linear start near zero. For small t, tanh(x) tracks x closely, matching free acceleration.
Drag slows acceleration. By 10 seconds, speed reaches 48.20 m/s and eases toward the asymptote.
Asymptotic cap. At 30 seconds, speed settles to terminal velocity 50.00 m/s.
Example 3 — Verify Saturation at Large Values and Infinities
Check that math.tanh() handles 1000, inf, and -inf without overflowing.
python
import math
print(math.tanh(1000), math.tanh(-1000))
print(math.tanh(float("inf")), math.tanh(float("-inf")))
print(math.copysign(1.0, math.tanh(-0.0)))
Output
1.0 -1.0
1.0 -1.0
-1.0
How It Works
No overflow at 1000. Whereas sinh(1000) raises OverflowError, tanh(1000) returns 1.0.
Infinite limits match. Passing inf and -inf yields exact 1.0 and -1.0.
Signed zero preserved. By IEEE 754 convention, tanh(-0.0) remains -0.0.
Frequently Asked Questions
No. For large positive or negative inputs it saturates smoothly to 1.0 or -1.0 without overflowing.
Strictly between -1.0 and 1.0 mathematically, though float rounding produces exact 1.0 or -1.0 once |x| >= 19.07.
1.0 (and -1.0 for -inf).
Use math.atanh(y) for inputs strictly between -1 and 1.
Because it maps arbitrary scores smoothly into [-1, 1] while keeping zero mapped to zero.