Tanh: Squashing Values Around Zero

Activation FunctionsEasy+10 XP+10

Tanh: Squashing Values Around Zero

Sigmoid squashes every input into (0, 1), so its output is always positive — a layer of sigmoids tends to push its next layer's weighted sums in one consistent direction, which slows learning down. Tanh fixes this by squashing into (-1, 1) instead, centered on zero:

tanh⁡(x)=ex−e−xex+e−x\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}tanh(x)=ex+e−xex−e−x​

Task: write tanh_activation(values) applying this element-wise, rounded to 4 decimal places.

  • Zero maps to exactly zero — tanh is an odd function, so negative inputs mirror positive ones around it.
  • Large |x| saturates toward -1 or 1, just like sigmoid saturates toward 0 or 1.

Examples

values = [-2.0, -0.5, 0.0, 1.5, 3.0]
returns [-0.964, -0.4621, 0.0, 0.9051, 0.9951]
values = [-10.0, 10.0]
returns [-1.0, 1.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run