-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathTanh.cs
More file actions
51 lines (45 loc) · 1.79 KB
/
Tanh.cs
File metadata and controls
51 lines (45 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
namespace Algorithms.Numeric;
/// <summary>
/// Implementation of the Hyperbolic Tangent (Tanh) function.
/// Tanh is an activation function that takes a real number as input and squashes
/// the output to a range between -1 and 1.
/// It is defined as: tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x)).
/// https://en.wikipedia.org/wiki/Hyperbolic_function#Hyperbolic_tangent.
/// </summary>
public static class Tanh
{
/// <summary>
/// Compute the Hyperbolic Tangent (Tanh) function for a single value.
/// The Math.Tanh() method is used for efficient and accurate computation.
/// </summary>
/// <param name="input">The input real number.</param>
/// <returns>The output real number in the range [-1, 1].</returns>
public static double Compute(double input)
{
// For a single double, we can directly use the optimized Math.Tanh method.
return Math.Tanh(input);
}
/// <summary>
/// Compute the Hyperbolic Tangent (Tanh) function element-wise for a vector.
/// </summary>
/// <param name="input">The input vector of real numbers.</param>
/// <returns>The output vector of real numbers, where each element is in the range [-1, 1].</returns>
public static double[] Compute(double[] input)
{
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
if (input.Length == 0)
{
throw new ArgumentException("Array is empty.");
}
var outputVector = new double[input.Length];
for (var index = 0; index < input.Length; index++)
{
// Apply Tanh to each element using the optimized Math.Tanh method.
outputVector[index] = Math.Tanh(input[index]);
}
return outputVector;
}
}