![](./write-blog/images/99505489-22-acos-Method.png)
Exploring the acos() Method in Java: A Comprehensive Guide
Table of Content:
Description
On this tutorial, we will be showing a java example on how to use the
acos(value a)
method of Math Class. The acos(value a)
returns the arc cosine of the method argument value. The following rule must be noted
- If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
The arc cosine of value is basically just the inverse cosine of a value. To further illustrate this below is the equation.
acos(a) = cos-1a
Most of the methods of the Math class is static and the acos() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. Use the method in the format Math.acos(a).
The method returns the arccosine of the specified double value.
Syntax
double acos(double d)
Parameters
Here is the detail of parameters ?
-
d ? A double data type.
Return Value
-
This method returns the arccosine of the specified double value.
Example
public class MathACos { public static void main(String args[]) { double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The arccosine of %.4f is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.acos(Math.cos(radians)))); } }
Output
This will produce the following result ?The value of pi is 3.1416 The arccosine of 0.7071 is 45.0000 degrees Press any key to continue . . .
Example
Below is a java code demonstrates the use of acos()
method of Math class. The example presented might be
simple however it shows the behavior of the acos() method.
import java.util.Scanner; /* * This example source code demonstrates the use of * acos() method of Math class */ public class MathAcosExample { public static void main(String[] args) { // Ask for user input System.out.print("Enter a value:"); // use scanner to read the console input Scanner scan = new Scanner(System.in); // Assign the user to String variable String s = scan.nextLine(); // close the scanner object scan.close(); // get the arc cosine value of the user input double acosValue = Math.acos(Double.parseDouble(s)); System.out.println("arc cosine of " + s + " is " + acosValue); } }
Output
Enter a value:0.76 arc cosine of 0.76 is 0.7074832117793429 Press any key to continue . . .
The above java example source code demonstrates the use of acos() method of Math class. We simply ask for user input and we use the Scanner class to parse it. Since we have used the nextLine() method to get the console value, and the return data type is String thus we have used the Double.parseDouble() to transform it into double. We have to convert it first to double because the acos() method accepts double method argument.