Skip to content
DeepForgeby svx
All problems
EasyDeep Learningdl-008

Tanh (Vector)

Problem

Apply the hyperbolic tangent element-wise: tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x)).

The signature is tanh_vector(x). Use a numerically stable branch so that large magnitudes saturate to 1.0 or -1.0 instead of overflowing.

Hint

Use exp(-2x) for x >= 0 so the exponent never overflows.

Test cases

case 1
in: [[0]]
expected: [0]
case 2
in: [[1000,-1000]]
expected: [1,-1]
case 3
in: [[1,-1]]
expected: [0.761594156,-0.761594156]
case 4
in: [[0.5,2,-0.25]]
expected: [0.4621171573,0.9640275801,-0.2449186624]
Starter codePython
import math
def tanh_vector(x):
    # Your code here
    pass

4 test cases · run your code against them in the editor