double tanh(double x) { if (x > 20) return 1.0; if (x < -20) return -1.0; double e2x = math.exp(2 * x); return (e2x - 1) / (e2x + 1); }