Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get the Trigonometric inverse cosine in Python
The inverse cosine (arccos) is a multivalued function that returns the angle whose cosine equals a given value. In NumPy, the arccos() function returns angles in the range [0, ?] radians. For real-valued inputs, it always returns real output, while invalid values (outside [-1, 1]) return nan.
To find the trigonometric inverse cosine, use the numpy.arccos() method. The method returns the angle of the array intersecting the unit circle at the given x-coordinate in radians [0, ?].
Syntax
numpy.arccos(x, out=None, where=True)
Parameters
The function accepts the following parameters ?
- x ? The x-coordinate on the unit circle. For real arguments, the domain is [-1, 1]
- out (optional) ? A location into which the result is stored
- where (optional) ? Condition to broadcast over the input
Basic Examples
Let's find the inverse cosine for common values ?
import numpy as np
# Finding arccos for boundary values
print("arccos(1):", np.arccos(1))
print("arccos(-1):", np.arccos(-1))
print("arccos(0):", np.arccos(0))
print("arccos(0.5):", np.arccos(0.5))
arccos(1): 0.0 arccos(-1): 3.141592653589793 arccos(0): 1.5707963267948966 arccos(0.5): 1.0471975511965979
Working with Arrays
The function also works with NumPy arrays ?
import numpy as np
# Array of cosine values
values = np.array([1, 0.5, 0, -0.5, -1])
angles = np.arccos(values)
print("Input values:", values)
print("Arccos angles (radians):", angles)
print("Arccos angles (degrees):", np.degrees(angles))
Input values: [ 1. 0.5 0. -0.5 -1. ] Arccos angles (radians): [0. 1.04719755 1.57079633 2.0943951 3.14159265] Arccos angles (degrees): [ 0. 60. 90. 120. 180.]
Handling Invalid Input
Values outside the domain [-1, 1] return nan ?
import numpy as np
# Testing with invalid values
invalid_values = np.array([1.5, -2, 0.8])
result = np.arccos(invalid_values)
print("Input:", invalid_values)
print("Result:", result)
Input: [ 1.5 -2. 0.8] Result: [ nan nan 0.64350111]
Common Use Cases
| Input Value | Angle (radians) | Angle (degrees) | Description |
|---|---|---|---|
| 1 | 0 | 0° | Cosine of 0° |
| 0 | ?/2 | 90° | Cosine of 90° |
| -1 | ? | 180° | Cosine of 180° |
Conclusion
The numpy.arccos() function calculates inverse cosine values, returning angles in radians within [0, ?]. Use np.degrees() to convert results to degrees when needed.
