numpy.arctan2 () in Python

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |

Syntax

numpy.arctan2(x1, x2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) = ufunc ’arctan2’
Parameters
x1 array_like, real-valued
y-coordinates.
x2 array_like, real-valued
x-coordinates. If x1.shape != x2.shape , they must be broadcastable to a common shape (which becomes the shape of the output).
out ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
where array_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
**kwargs
For other keyword-only arguments, see the ufunc docs.
Returns
angle ndarray
Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.
We will cover NumPy arctan2. Along with that, for a better general understanding, we will also look at its syntax and parameter. Then, we will see the application of the whole theoretical part through some examples. But first, let’s try to analyze the function through its definition. First, arctan means the inverse of a tan function. Now the NumPy arctan2 function helps us to calculate the arc tan value between X1 and X2 in radians. Here, X1 and 2 are parameters that we will discuss later. As we progress through this article, things will become clearer for you. Next, let’s look at the syntax associated with it.
The method numpy.arctan2() calculates the element-wise arctangent of arr1 / arr2 and selects the quadrant correctly. The quadrant is chosen so that arctan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through point (1, 0) and the ray ending at the origin and passing through point (x2, x1).
Arctan2 is a 4-quadrant inverse function. Taking this into account, it gives a value between 0 and 2pi. The range of this function is -180 to 180 degrees. These are the 2 key points that distinguish Arctan2 from arctan features.

Difference Between Arctan and Arctan2

In this section we will discuss the difference between 2 Numpy functions.
NumPy arctan NumPy arctan2
arctan is a 2 quadrant inverse function. arctan2 is a 4 quadrant inverse function.
The range of the arctan function is from -90 to 90 degree. The range for arctan2 is -180 to 180 degree.
This function accepts a single array. This function as discussed take 2 input arrays.
Now we are finished with the theoretical part for NumPy arctan2. This section explores how this feature works and how it helps us get the output we want. We’ll start with an elementary example and gradually move on to a more complicated example.

NumPy Arctan2 Example

import numpy as ppool
y=[1,1]
x=[1,1.732]
print(ppool.arctan2(y,x))

[0.78539816 0.52361148]
Above we see a simple example of our arctan2 function. Now let’s walk line by line and understand how we got the result. First, we imported the NumPy function. Then we defined our 2 sets of the array. By using the syntax of our function and the print statement, we get the result we want. Here both values ‚Äã‚Äãare given in radians. Now if you want to check the result to some extent. To do this, we need to use this particular method:
Angle in degree = angle in radian * 180/pi
If we make calculations on our results, we get a 45 and 30-degree answer. Here we considered pi to 3.14. The responses match and therefore the result is verified.

Numpy Arctan() Example #2

Now suppose that we also want to obtain the values ‚Äã‚Äãin degrees. It is a simple process and can be done with the help of the for loop and the formula discussed above. Let’s see how:
import numpy as ppool
degree=0
y=[-1,1.732]
x=[2,1]
b=ppool.arctan2(y,x)
print(b)
for vals in b:
         degree=vals*(180/3.14)
         print(degree)

Output:

[-0.46364761  1.04718485]
-26.578525356734104
60.02970472117416
See how we get the values ‚Äã‚Äãin radians and degrees. All steps are similar to the first example. The only difference we used a "for loop". If you want something simpler we can also use another method
import numpy as ppool
y=[-1,1.732]
x=[2,1]
b=ppool.arctan2(y,x)*(180/3.14)
print(b)
Here all you need to do is multiply the value (180 / 3.14) or (180 / ppool.pi) by the array. You can definitely use this method on the for loop method. But either way, you will get the desired output which is a degree value.

Output:

[-26.57852536  60.02970472]

NumPy Arctan2 Example #3

def doa(self, receiver, source):
        ’’’ Computes the direction of arrival wrt a source and receiver ’’’

        s_ind = self.key2ind(source)
        r_ind = self.key2ind(receiver)

        # vector from receiver to source
        v = self.X[:,s_ind] - self.X[:,r_ind]

        azimuth = np.arctan2(v[1], v[0]) elevation = np.arctan2(v[2], la.norm(v[:2])) azimuth = azimuth + 2*np.pi if azimuth < 0. else azimuth elevation = elevation + 2*np.pi if elevation < 0. else elevation return np.array([azimuth, elevation])

NumPy Arctan2 Example #4

def mtx_freq2visi(M, p_mic_x, p_mic_y):
    """
    build the matrix that maps the Fourier series to the visibility
    :param M: the Fourier series expansion is limited from -M to M
    :param p_mic_x: a vector that constains microphones x coordinates
    :param p_mic_y: a vector that constains microphones y coordinates
    :return:
    """
    num_mic = p_mic_x.size
    ms = np.reshape(np.arange(-M, M + 1, step=1), (1, -1), order=’F’)
    G = np.zeros((num_mic * (num_mic - 1), 2 * M + 1), dtype=complex, order=’C’)
    count_G = 0
    for q in range(num_mic):
        p_x_outer = p_mic_x[q]
        p_y_outer = p_mic_y[q]
        for qp in range(num_mic):
            if not q == qp:
                p_x_qqp = p_x_outer - p_mic_x[qp]
                p_y_qqp = p_y_outer - p_mic_y[qp]
                norm_p_qqp = np.sqrt(p_x_qqp ** 2 + p_y_qqp ** 2)
                phi_qqp = np.arctan2(p_y_qqp, p_x_qqp) G[count_G, :] = (-1j) ** ms * sp.special.jv(ms, norm_p_qqp) * np.exp(1j * ms * phi_qqp) count_G += 1 return G

NumPy Arctan2 Example #5

def vector_angle(u, v, direction=None):
    ’’’
    vector_angle(u, v) yields the angle between the two vectors u and v. The optional argument 
    direction is by default None, which specifies that the smallest possible angle between the
    vectors be reported; if the vectors u and v are 2D vectors and direction parameters True and
    False specify the clockwise or counter-clockwise directions, respectively; if the vectors are
    3D vectors, then direction may be a 3D point that is not in the plane containing u, v, and the
    origin, and it specifies around which direction (u x v or v x u) the the counter-clockwise angle
    from u to v should be reported (the cross product vector that has a positive dot product with
    the direction argument is used as the rotation axis).
    ’’’
    if direction is None:
        return np.arccos(vector_angle_cos(u, v))
    elif direction is True:
        return np.arctan2(v[1], v[0]) - np.arctan2(u[1], u[0]) elif direction is False: return np.arctan2(u[1], u[0]) - np.arctan2(v[1], v[0]) else: axis1 = normalize(u) axis2 = normalize(np.cross(u, v)) if np.dot(axis2, direction) < 0: axis2 = -axis2 return np.arctan2(np.dot(axis2, v), np.dot(axis1, v))

NumPy Arctan2 Example #6

def __init__(self, line):
        data = line.split(’ ’)
        data[1:] = [float(x) for x in data[1:]]
        self.classname = data[0]
        self.xmin = data[1] 
        self.ymin = data[2]
        self.xmax = data[1]+data[3]
        self.ymax = data[2]+data[4]
        self.box2d = np.array([self.xmin,self.ymin,self.xmax,self.ymax])
        self.centroid = np.array([data[5],data[6],data[7]])
        self.unused_dimension = np.array([data[8],data[9],data[10]])
        self.w = data[8]
        self.l = data[9]
        self.h = data[10]
        self.orientation = np.zeros((3,))
        self.orientation[0] = data[11]
        self.orientation[1] = data[12]
        self.heading_angle = -1 * np.arctan2(self.orientation[1], self.orientation[0])

np.arctan2 Example #7

def stanleyControl(state, cx, cy, cyaw, last_target_idx):
    """
    :param state: (State object)
    :param cx: ([float])
    :param cy: ([float])
    :param cyaw: ([float])
    :param last_target_idx: (int)
    :return: (float, int, float)
    """
    # Cross track error
    current_target_idx, error_front_axle = calcTargetIndex(state, cx, cy)

    if last_target_idx >= current_target_idx:
        current_target_idx = last_target_idx

    # theta_e corrects the heading error
    theta_e = normalizeAngle(cyaw[current_target_idx] - state.yaw)
    # theta_d corrects the cross track error
    theta_d = np.arctan2(K_STANLEY_CONTROL * error_front_axle, state.v) # Steering control delta = theta_e + theta_d return delta, current_target_idx, error_front_axle

np arctan2 Example #8

def calcTargetIndex(state, cx, cy):
    """
    :param state: (State object)
    :param cx: [float]
    :param cy: [float]
    :return: (int, float)
    """
    # Calc front axle position
    fx = state.x + CAR_LENGTH * np.cos(state.yaw)
    fy = state.y + CAR_LENGTH * np.sin(state.yaw)

    # Search nearest point index
    dx = [fx - icx for icx in cx]
    dy = [fy - icy for icy in cy]
    d = [np.sqrt(idx ** 2 + idy ** 2) for (idx, idy) in zip(dx, dy)]
    error_front_axle = min(d)
    target_idx = d.index(error_front_axle)

    target_yaw = normalizeAngle(np.arctan2(fy - cy[target_idx], fx - cx[target_idx]) - state.yaw) if target_yaw > 0.0: error_front_axle = - error_front_axle return target_idx, error_front_axle

NumPy Arctan2 Example #9

def vehicle_flat_reverse(zflag, params={}):
    # Get the parameter values
    b = params.get(’wheelbase’, 3.)

    # Create a vector to store the state and inputs
    x = np.zeros(3)
    u = np.zeros(2)

    # Given the flat variables, solve for the state
    x[0] = zflag[0][0]  # x position
    x[1] = zflag[1][0]  # y position
    x[2] = np.arctan2(zflag[1][1], zflag[0][1]) # tan(theta) = ydot/xdot # And next solve for the inputs u[0] = zflag[0][1] * np.cos(x[2]) + zflag[1][1] * np.sin(x[2]) thdot_v = zflag[1][2] * np.cos(x[2]) - zflag[0][2] * np.sin(x[2]) u[1] = np.arctan2(thdot_v, u[0]**2 / b) return x, u # Function to compute the RHS of the system dynamics

np.arctan2 Example #10

def GetNeighborCells(self, p, nr, dp = None):
        ’’’
        Returns all cells no more than a given distance in any direction
        from a specified cell
        p:      The cell of which to get the neighbors
        nr:     Neighbor radius
        dp:     Direction preference
        ’’’
        pi, pj, pk = p
        tqm = self.qm * self.qp
        nc = [(pi - i * tqm, pj - j * tqm, pk) for i in range(-nr, nr + 1) for j in range(-nr, nr + 1)]
        if dp is not None:                      #Sort points based on direction preference
            dpa = np.arctan2(dp[1], dp[0]) #Get angle of direction prefered #Prefer directions in the direction of dp; sort based on magnitude of angle from last direction nc = sorted(nc, key = lambda t : np.abs(np.arctan2(t[1], t[0]) - dpa)) return nc #Gets the current 3d position of the player
In this article, we cover NumPy’s arctan2. In addition, we also saw its syntax and parameters. For better understanding, we saw some examples. In the end, we can conclude that NumPy arctan2 is a function that this function helps us to find the inverse tan value between 2 points. By default it returns the value in radians, but we can convert it to degrees using the methods discussed above. We hope this article has clarified all your doubts. But in case you have any unresolved questions, feel free to write them down in the comments section. Having read that, why not read about the following identity matrix.

Python atan or atan2, what should I use?

StackOverflow question

My formula f=arctan(ImZ/ReZ) There are two options: Option 1 (atan):
ImZ=-4.593172163003
ImR=-4.297336384845

>>> z=y/x
>>> f1=math.atan(z)
>>> f1
0.8186613519278327
Option 2 (atan2)
>>> f=math.atan2(y,x)
>>> f
-2.3229313016619604
Why are these two results different?

Answer:

Atan takes single argument and Atan2 takes two arguments.The purpose of using two arguments instead of one is to gather information on the signs of the inputs in order to return the appropriate quadrant of the computed angle, which is not possible for the single-argument Atan atan2 results for each x,y Atan2 result is always between -pi and pi. Reference: https://en.wikipedia.org/wiki/Atan2

Archived version

numpy.arctan2 (arr1, arr2, casting = & # 39; same_kind & # 39 ;, order = & # 39; K & # 39 ;, dtype = None, ufunc & # 39; arctan & # 39;) : Calculates the element-wise arctangent of arr1 / arr2 by choosing the correct quadrant. The quadrant is chosen so that arctan2 (x1, x2) is the angle sign in radians between a ray ending at the origin and passing through point (1, 0) and a ray ending at the origin and passing through through point (x2) x1).
Parameters: arr1: [array_like] real valued; y-coordinates arr2: [array_like] real valued; x-coordinates. It must match shape of y-cordinates. out: [ndarray, array_like [ OPTIONAL ]] array of same shape as x . where: [array_like, optional] True value means to calculate the universal functions (ufunc) at that position, False value means to leave the value in the output alone. Note: 2pi Radians = 360 degrees The convention is to return the angle z whose real part lies in [-pi / 2 , pi / 2]. Return: Element-wise arc tangent of arr1 / arr2. The values ​​are in the closed interval [-pi / 2, pi / 2].
Code # 1: Work
# Python3 program explaining # arctan2 () function   import numpy as np   arr1 = [ - 1 , + 1 , + 1 , - 1 ] arr2 <c ode class="keyword"> = [ - 1 , - 1 , + 1 , + 1 ] </c ode>    ans = np.arctan2 (arr2, arr1) * 180 / np.pi   print ( "x-coordinates:" , arr1) print ( "y-coordin ates: " , arr2)    print ( "arctan2 values:" , ans)
Output:
 x-coordinates: [-1, 1, 1, -1] y-coordinates: [-1, -1, 1, 1] arctan2 values: [-135. -45. 45. 135.]
Code # 2: Work
# Python3 program showing # arctan2 () functions   import numpy as np   a = np.arctan2 ([ 0. , 0. , np.inf ], [ + 0. , - 0. , np.inf])   b = np.arctan2 ([ 1. , - 1. ], [ 0. , 0. ])   print ( " a : " , a)    print ( "b:" , b )
Output:
 a: [0. 3.14159265 0.78539816] b: [1.57079633 -1.57079633]
Links: arctan2.html#numpy.arctan2>https://docs.scipy.org/doc/numpy-1.13.0/reference/g enerated / numpy.arctan2.html # numpy.arctan2 ,

numpy.arctan2 () in Python __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

numpy.arctan2 () in Python __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically