📘
Hard Tanh
EasyDeep Learning
Problem Statement
Implement the "Hard Tanh" function which clamps values to a range.
Background
Hard Tanh is a computationally cheaper approximation of the tanh function:
- Returns −1 if x<−1
- Returns 1 if x>1
- Returns x if −1≤x≤1
It's essentially a piecewise linear function that clips values outside [-1, 1].
Your Task
Write a function hard_tanh(values) that applies Hard Tanh element-wise to a list.
Output Format
Return a list of floats with Hard Tanh applied. Round each value to 4 decimal places.
Example:
Input:
values=[-1.5, 0.5, 2.0]
Output:
[-1.0, 0.5, 1.0]
Reasoning:
-1.5 < -1 → clamped to -1.0; 0.5 is in [-1,1] → stays 0.5; 2.0 > 1 → clamped to 1.0.
Constraints:
- -1000 <= x <= 1000 for each element
- List length: 1 to 100 elements
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.