Java Math cos()

The syntax of the cos() method is:

Math.cos(double angle)

Here, cos() is a static method. Hence, we are accessing the method using the class name, Math.


cos() Parameters

The cos() method takes a single parameter.

  • angle - angle whose trigonometric cosine is to be returned

Note: The value of the angle is in radians.


cos() Return Value

  • returns the trigonometric cosine of the specified angle
  • returns NaN if the specified angle is NaN or infinity

Example 1: Java Math cos()

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create variable in Degree
    double a = 30;
    double b = 45;

    // convert to radians
    a = Math.toRadians(a);
    b = Math.toRadians(b);

    // print the cosine value
    System.out.println(Math.cos(a));  // 0.8660254037844387
    System.out.println(Math.cos(b));  // 0.7071067811865476
  }
}

In the above example, we have imported the java.lang.Math package. This is important if we want to use methods of the Math class. Notice the expression,

Math.cos(a)

Here, we have directly used the class name to call the method. It is because cos() is a static method.

Note: We have used the Java Math.toRadians() method to convert all the values into radians. It is because as per the official documentation, the cos() method takes the angle as radians.


Example 2: Math cos() Returns NaN

import java.lang.Math;

class Main {
  public static void main(String[] args) {

    // create variable
    // square root of negative number
    // results in not a number (NaN)
    double a = Math.sqrt(-5);

    // Using Double to implement infinity
    double infinity = Double.POSITIVE_INFINITY;

    // print the cosine  value
    System.out.println(Math.cos(a));  // NaN
    System.out.println(Math.cos(infinity));  // NaN
  }
}

Here, we have created a variable named a.

  • Math.cos(a) - returns NaN because square root of a negative number (-5) is not a number

The Double.POSITIVE_INFINITY is a field of Double class. It is used to implement infinity in Java.

Note: We have used the Java Math.sqrt() method to compute the square root of a number.


Also Read:

Did you find this article helpful?