The Math.tan() method of java.lang.Math class calculates the trigonometric tangent of an angle. Suppose there is a right-angled triangle, so tan(angle) is the opposite side divided by the adjacent side.
- If the argument is NaN or an infinity, then the result returned is NaN.
- If the argument is zero, then the result is a zero with the same sign as the argument.
Syntax of Math tan() Method
public static double tan(double angle)
- Parameters: The function has one mandatory parameter, "angle" which is in radians.
- Returns: The function returns the trigonometric tangent of an angle.
Note: Convert degrees with Math.toRadians(degrees) before passing to tan().
Examples of Java Math tan() Method
Example 1: In this example, we will see the working of Math.tan() method with basic angles.
Java
// Java program to demonstrate working
// of java.lang.Math.tan() method
import java.lang.Math;
class Geeks {
public static void main(String args[]) {
double a = 30;
double b = Math.toRadians(a);
System.out.println(Math.tan(b));
a = 45;
b = Math.toRadians(a);
System.out.println(Math.tan(b));
a = 60;
b = Math.toRadians(a);
System.out.println(Math.tan(b));
a = 0;
b = Math.toRadians(a);
System.out.println(Math.tan(b));
}
}
Output0.5773502691896257
0.9999999999999999
1.7320508075688767
0.0
Explanation: Here, we convert each angle that are 30 degree, 45 degree, 60 degree, 0 degree, to radians and print the tangent value.
Example 2: In this example, we will see, what happens with NaN and infinity cases.
Java
// Java program to demonstrate working of
// java.lang.Math.tan() method when argument is NaN or Infinity
import java.lang.Math;
class Geeks {
public static void main(String args[]) {
double positiveInfinity = Double.POSITIVE_INFINITY;
double negativeInfinity = Double.NEGATIVE_INFINITY;
double nan = Double.NaN;
double result;
// argument is negative infinity
result = Math.tan(negativeInfinity);
System.out.println(result);
// argument is positive infinity
result = Math.tan(positiveInfinity);
System.out.println(result);
// argument is NaN
result = Math.tan(nan);
System.out.println(result);
}
}
Explanation: As we discussed earlier, here, NaN or infinite input produces NaN.
Explore
Basics
OOPs & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java