In Java, the tanh() method is a part of the java.lang.Math class. This method returns the hyperbolic tangent of a double value passed to it as an argument.
Mathematical Definition:
The hyperbolic tangent of any value a is defined as:
((ea - e-a)/2)/((ea + e-a)/2)
where, e is Euler's number, whose value is approximately equal to 2.71828. This method returns values between -1 and 1, and that's why this function becomes very useful in various mathematical applications.
In other words, the hyperbolic tangent of a number a can also be defined as:
tanh(a) = sinh(a)/cosh(a)
Special Cases: The tanh() method handles different cases which are listed below,
- If the argument is NaN, then the result is NaN.
- If the argument is positive infinity then the result will be +1.0.
- If the argument is negative infinity then the result will be -1.0.
- If the argument is zero, then the result is zero with the same sign as that of the argument a.
Syntax of tanh() Method
public static double tanh(double a)
- Parameter: This method takes a single parameter a, which is the value whose hyperbolic tangent is to be returned.
- Return Type: This method returns the hyperbolic tangent value of the argument.
Now, we are going to discuss some examples for better understanding
Examples of Java Math tanh() Method
Example 1: In this example, we will see the basic usage of tanh() method.
// Java program to demonstrate working
// of Math.tanh() method
import java.lang.Math;
class Geeks {
public static void main(String args[]) {
double a = 3.5;
System.out.println(Math.tanh(a));
a = 90.328;
System.out.println(Math.tanh(a));
a = 0;
System.out.println(Math.tanh(a));
}
}
Output
0.9981778976111987 1.0 0.0
Explanation: Here, we are calculating the hyperbolic tangent for given double value. For a=3.5, the result will be 0.9981778976111987 and for a=90.328, the result will be 1.0 and for a=0, the result is 0.0
Example 2: In this example, we will see how tanh() method handles NaN and Infinity.
// Java program to demonstrate working
// of Math.tanh() method in NaN and infinity case
import java.lang.Math;
public class Geeks {
public static void main(String[] args) {
double p = Double.POSITIVE_INFINITY;
double n = Double.NEGATIVE_INFINITY;
double nan = Double.NaN;
double res;
// here argument is negative infinity
res = Math.tanh(n);
System.out.println(res);
// here argument is positive infinity
res = Math.tanh(p);
System.out.println(res);
// here argument is NaN
res = Math.tanh(nan);
System.out.println(res);
}
}
Output
-1.0 1.0 NaN