Java Math acos()

The Java Math acos() method returns the arc cosine of the specified value.

The arc cosine is the inverse of the cosine function.

The syntax of the acos() method is:

Math.acos(double num)

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


acos() Parameters

The acos() method takes a single parameter.

  • num - number whose arc cosine is to be returned. It should be always less than 1.

acos() Return Value

  • returns the arc cosine of the specified number
  • returns NaN if the specified number is NaN or greater than 1

Note: The returned value is an angle between 0.0 to pi.


Example 1: Java Math acos()

import java.lang.Math;

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

    // create variable
    double a = 0.5;
    double b = 0.79;
    double c = 0.0;

    // print the arc cosine value
    System.out.println(Math.acos(a));  // 1.0471975511965979
    System.out.println(Math.acos(b));  // 0.6599873293874984
    System.out.println(Math.acos(c));  // 1.5707963267948966
  }
}

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.acos(a)

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


Example 2: Math acos() Returns NaN

import java.lang.Math;

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

    // create variable
    double a = 2;

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

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

Here, we have created two variables named a and b.

  • Math.acos(a) - returns NaN because value of a is greater than 1.
  • Math.acos(b) - returns NaN because square root of a negative number (-5) is not a number.

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