YouTip LogoYouTip

Ref Math Atan2

## Python math.atan2() Method The `math.atan2()` method is a built-in function in Python's standard `math` module. It returns the arc tangent (inverse tangent) of the quotient $y / x$ in radians. Unlike the standard `math.atan(y / x)` function, `math.atan2(y, x)` accepts both the $y$ and $x$ coordinates as separate arguments. This allows it to correctly determine the signs of both inputs and place the resulting angle in the correct quadrant of the Cartesian plane. --- ### Introduction to Quadrant Awareness The returned value is a float representing the angle $\theta$ in radians between the positive x-axis and the point $(x, y)$. * **Range:** The resulting angle is always between $-\pi$ and $\pi$ (inclusive of $-\pi$ and $\pi$, i.e., $[-\pi, \pi]$ radians, which corresponds to $-180^\circ$ to $180^\circ$). * **Sign Handling:** It automatically handles the signs of $x$ and $y$ to resolve the correct quadrant, which a simple $y/x$ division cannot do (for example, distinguishing between $(-y)/(-x)$ in Quadrant III and $y/x$ in Quadrant I). --- ### Syntax ```python import math math.atan2(y, x) ``` #### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **`y`** | `float` or `int` | **Required.** The y-coordinate (vertical axis). Can be positive or negative. | | **`x`** | `float` or `int` | **Required.** The x-coordinate (horizontal axis). Can be positive or negative. | #### Return Value * **Type:** `float` * **Description:** Returns the arc tangent of $y/x$ in radians, ranging from $-\pi$ to $\pi$. --- ### Code Examples #### Basic Usage The following example demonstrates how to calculate the arc tangent for different coordinate pairs: ```python import math # Calculate the arc tangent of y/x print(math.atan2(8, 5)) # Quadrant I (both positive) print(math.atan2(20, 10)) # Quadrant I (both positive) print(math.atan2(34, -7)) # Quadrant II (positive y, negative x) ``` **Output:** ```text 1.0121970114513341 1.1071487177940904 1.7738415440483617 ``` --- ### Advanced Examples & Considerations #### 1. Converting Radians to Degrees Because `math.atan2()` returns values in radians, you can use `math.degrees()` to convert the result into degrees ($0^\circ$ to $\pm180^\circ$): ```python import math radians = math.atan2(1, -1) # Quadrant II degrees = math.degrees(radians) print(f"Radians: {radians}") print(f"Degrees: {degrees}Β°") ``` **Output:** ```text Radians: 2.356194490192345 Degrees: 135.0Β° ``` #### 2. Handling Zero Values Unlike standard division (`y / x`), which raises a `ZeroDivisionError` if $x = 0$, `math.atan2(y, x)` safely handles zero values: ```python import math # Point lies on the positive y-axis (90 degrees) print(math.atan2(1, 0)) # Output: 1.5707963267948966 (pi / 2) # Point lies on the negative y-axis (-90 degrees) print(math.atan2(-1, 0)) # Output: -1.5707963267948966 (-pi / 2) # Origin point (0, 0) print(math.atan2(0, 0)) # Output: 0.0 ```
← Ref Math CosRef Math Asinh β†’