The numpy.arctan2()
method computes the element-wise arc tangent (inverse tangent) of y / x
, where y
and x
are arrays.
Example
import numpy as np
# create arrays for y and x coordinates
y = np.array([1, -1, 1, -1])
x = np.array([1, 1, -1, -1])
# compute the element-wise arc tangent of y / x
result = np.arctan2(y, x)
# print the resulting angles
print(result)
# Output: [ 0.78539816 -0.78539816 2.35619449 -2.35619449]
arctan2() Syntax
The syntax of the numpy.arctan2()
method is:
numpy.arctan2(y, x, out = None, where = True, order = 'K', dtype = None)
arctan2() Arguments
The numpy.arctan2()
method takes the following arguments:
y
- an array containing y-coordinate valuesx
- an array containing x-coordinate valuesout
(optional) - the output array where the result will be storedwhere
(optional) - a boolean array or condition specifying which elements should be updateddtype
(optional) - the data type of the returned output
arctan2() Return Value
The numpy.arctan2()
method returns an array with the same shape as y and x, containing the element-wise arc tangent of y / x
.
Example 1: Optional out and where Arguments in arctan2()
import numpy as np
# create arrays for y and x coordinates
y = np.array([1, -1, 1, -1])
x = np.array([1, 1, -1, -1])
# create a condition array
condition = np.array([True, False, True, False])
# create an array of zeros with the same shape as y, using float data type
result = np.zeros_like(y, dtype = float)
# compute the element-wise arc tangent
# of y / x, using the provided condition
# and store the result in the result array
np.arctan2(y, x, out = result, where = condition)
# print the resulting angles
print(result)
Output
[0.78539816 0. 2.35619449 0. ]
In the above example, arctan2()
calculates the element-wise arc tangent of the division between y and x for elements where the corresponding value in the condition array is True
.
And by setting out = result
, the output is stored in the result array.
Example 2: Use of dtype Argument in arctan2()
import numpy as np
# create arrays for y and x coordinates
y = np.array([2.5, -3.8, 1.2, -4.6])
x = np.array([-1.5, 2.7, -3.1, 0.9])
# compute arctan2 with float32 dtype
resultFloat = np.arctan2(y, x, dtype = np.float32)
# compute arctan2 with float64 dtype
resultDouble = np.arctan2(y, x, dtype = np.float64)
# print results
print("Result with float32 dtype:")
print(resultFloat)
print("\nResult with float64 dtype:")
print(resultDouble)
Output
Result with float32 dtype: [ 2.1112158 -0.9530406 2.772259 -1.3775848] Result with float64 dtype: [ 2.11121583 -0.9530406 2.772259 -1.37758484]
By specifying different dtype
values, we can control the precision and memory usage of the resulting array.
In this example, resultFloat has the float32
data type, while resultDouble has the float64
data type.