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.
xxxxxxxxxx
1
public class CustomMath {
2
3
public static void main(String[] args) {
4
System.out.println( Math.acos( -2 ) ); // NaN
5
System.out.println( Math.acos( -1 ) ); // 3.1415926535897930 -> 180
6
System.out.println( Math.acos( -0.5 ) ); // 2.0943951023931957 -> ~120
7
System.out.println( Math.acos( 0 ) ); // 1.5707963267948966 -> 90
8
System.out.println( Math.acos( 0.5 ) ); // 1.0471975511965979 -> ~60
9
System.out.println( Math.acos( 1 ) ); // 0 -> 0
10
System.out.println( Math.acos( 2 ) ); // NaN
11
12
System.out.println( Math.acos( 0.7071067811865476 ) ); // 0.7853981633974483 -> 45 deg
13
System.out.println( Math.acos( 0.8660254037844387 ) ); // 0.5235987755982987 -> 30 deg
14
15
System.out.println(Math.acos( Math.cos( Math.PI / 4))); // 0.7853981633974483 -> pi/4 (45deg)
16
System.out.println(Math.cos( Math.acos( Math.PI / 4))); // 0.7853981633974483 -> pi/4 (45deg)
17
}
18
}
Another way to look at acos
function:
xxxxxxxxxx
1
public class CustomMath {
2
3
static double calculateAngle(double b, double h) {
4
return Math.acos(b / h);
5
}
6
7
public static void main(String[] args) {
8
/*
9
10
|\
11
| \ h
12
a | \
13
|__*\ <- angle
14
b
15
16
*/
17
18
double a, b, h;
19
20
// a, b and h build isosceles right triangle
21
a = 3;
22
b = a;
23
h = Math.sqrt(a * a + b * b);
24
System.out.println( CustomMath.calculateAngle(b, h) ); // 0.7853981633974483 <- 45 degrees
25
26
// a, b and h build half of equilateral triangle
27
a = 3;
28
b = a * Math.sqrt(3);
29
h = Math.sqrt(a * a + b * b);
30
System.out.println( CustomMath.calculateAngle(b, h) ); // 0.5235987755982987 <- ~30 degrees
31
32
// a, b and h are not able to build triangle
33
a = 3;
34
b = a;
35
h = 1;
36
System.out.println( CustomMath.calculateAngle(b, h) ); // NaN
37
}
38
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static double acos(double number) { ... } 6 7 }
|
Parameters |
|
Result |
If the value can not be calculated |
Description |
|
xxxxxxxxxx
1
public class CustomMath {
2
3
static double calculateAngle(double b, double h) {
4
double angle = Math.acos(b / h);
5
6
return (180 / Math.PI) * angle; // rad to deg conversion
7
}
8
9
public static void main(String[] args) {
10
/*
11
|\
12
| \ h
13
a | \
14
|__*\ <- angle
15
b
16
*/
17
18
double a, b, h;
19
20
// a, b and h build isosceles right triangle
21
a = 3;
22
b = a;
23
h = Math.sqrt(a * a + b * b);
24
System.out.println( calculateAngle(b, h) ); // 45 degrees
25
26
// a, b and h build half of equilateral triangle
27
a = 3;
28
b = a * Math.sqrt(3);
29
h = Math.sqrt(a * a + b * b);
30
System.out.println( calculateAngle(b, h) ); // ~30 degrees
31
32
// a, b and h are not able to build triangle
33
a = 3;
34
b = a;
35
h = 1;
36
System.out.println( calculateAngle(b, h) ); // NaN
37
}
38
}
39