EN
Java - Math.acos() method example
3
points
The Math.acos
function returns number in radians in the range 0 to Math.PI. Based on this function we are able to calculate the inverted cosine function value.
public class CustomMath {
public static void main(String[] args) {
System.out.println( Math.acos( -2 ) ); // NaN
System.out.println( Math.acos( -1 ) ); // 3.1415926535897930 -> 180
System.out.println( Math.acos( -0.5 ) ); // 2.0943951023931957 -> ~120
System.out.println( Math.acos( 0 ) ); // 1.5707963267948966 -> 90
System.out.println( Math.acos( 0.5 ) ); // 1.0471975511965979 -> ~60
System.out.println( Math.acos( 1 ) ); // 0 -> 0
System.out.println( Math.acos( 2 ) ); // NaN
System.out.println( Math.acos( 0.7071067811865476 ) ); // 0.7853981633974483 -> 45 deg
System.out.println( Math.acos( 0.8660254037844387 ) ); // 0.5235987755982987 -> 30 deg
System.out.println(Math.acos( Math.cos( Math.PI / 4))); // 0.7853981633974483 -> pi/4 (45deg)
System.out.println(Math.cos( Math.acos( Math.PI / 4))); // 0.7853981633974483 -> pi/4 (45deg)
}
}
Another way to look at acos
function:
public class CustomMath {
static double calculateAngle(double b, double h) {
return Math.acos(b / h);
}
public static void main(String[] args) {
/*
|\
| \ h
a | \
|__*\ <- angle
b
*/
double a, b, h;
// a, b and h build isosceles right triangle
a = 3;
b = a;
h = Math.sqrt(a * a + b * b);
System.out.println( CustomMath.calculateAngle(b, h) ); // 0.7853981633974483 <- 45 degrees
// a, b and h build half of equilateral triangle
a = 3;
b = a * Math.sqrt(3);
h = Math.sqrt(a * a + b * b);
System.out.println( CustomMath.calculateAngle(b, h) ); // 0.5235987755982987 <- ~30 degrees
// a, b and h are not able to build triangle
a = 3;
b = a;
h = 1;
System.out.println( CustomMath.calculateAngle(b, h) ); // NaN
}
}
1. Documentation
Syntax |
|
Parameters |
|
Result |
If the value can not be calculated |
Description |
|
2. Working with degrees
public class CustomMath {
static double calculateAngle(double b, double h) {
double angle = Math.acos(b / h);
return (180 / Math.PI) * angle; // rad to deg conversion
}
public static void main(String[] args) {
/*
|\
| \ h
a | \
|__*\ <- angle
b
*/
double a, b, h;
// a, b and h build isosceles right triangle
a = 3;
b = a;
h = Math.sqrt(a * a + b * b);
System.out.println( calculateAngle(b, h) ); // 45 degrees
// a, b and h build half of equilateral triangle
a = 3;
b = a * Math.sqrt(3);
h = Math.sqrt(a * a + b * b);
System.out.println( calculateAngle(b, h) ); // ~30 degrees
// a, b and h are not able to build triangle
a = 3;
b = a;
h = 1;
System.out.println( calculateAngle(b, h) ); // NaN
}
}