Implement the Tanh (Hyperbolic Tangent) activation function: tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x)).
Apply the formula element-wise, using a numerically stable formulation.
import math
def tanh(x: float) -> float:
if x > 20:
return 1.0
if x < -20:
return -1.0
e_pos = math.exp(x)
e_neg = math.exp(-x)
return (e_pos - e_neg) / (e_pos + e_neg)
def tanh_list(values: list[float]) -> list[float]:
return [round(tanh(v), 6) for v in values]e^x and e^{-x}.(e^x - e^{-x}) / (e^x + e^{-x}).