杰瑞科技汇

python numpy arctan

Of course! Here's a comprehensive guide to using the arctan function in Python with NumPy, covering everything from the basics to advanced use cases.

python numpy arctan-图1
(图片来源网络,侵删)

The Basics: numpy.arctan

The numpy.arctan function computes the element-wise arctangent (inverse tangent) of an array. The result is an angle in radians between -π/2 and π/2.

Syntax

numpy.arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

The most important argument is x, which can be a number, a list, or a NumPy array.

Key Points:

  • Input: A real number or an array of real numbers.
  • Output: The arctangent of the input, in radians. The output has the same shape as the input.
  • Domain: All real numbers ( to ).
  • Range: [-π/2, π/2] (approximately [-1.5708, 1.5708] radians).

Simple Examples

Let's start with the most common use cases.

Example 1: Arctangent of a Single Number

import numpy as np
# Arctangent of 1
# tan(π/4) = 1, so arctan(1) should be π/4
result = np.arctan(1)
print(f"arctan(1) = {result}")
print(f"This is approximately π/4: {np.pi / 4}")
# Arctangent of 0
# tan(0) = 0, so arctan(0) should be 0
result_zero = np.arctan(0)
print(f"\narctan(0) = {result_zero}")
# Arctangent of a large number
# As x approaches infinity, arctan(x) approaches π/2
result_large = np.arctan(1000)
print(f"\narctan(1000) ≈ {result_large}")
print(f"This is close to π/2: {np.pi / 2}")

Output:

python numpy arctan-图2
(图片来源网络,侵删)
arctan(1) = 0.7853981633974483
This is approximately π/4: 0.7853981633974483
arctan(0) = 0.0
arctan(1000) ≈ 1.5697963271282298
This is close to π/2: 1.5707963267948966

Example 2: Arctangent of an Array

numpy.arctan is vectorized, meaning it can operate on an entire array at once, which is much faster than looping.

import numpy as np
# Create an array of values
angles = np.array([-1, 0, 1, np.sqrt(3)]) # sqrt(3) is tan(π/3)
# Calculate arctan for each element
arctan_values = np.arctan(angles)
print("Original array:", angles)
print("Arctan values (in radians):", arctan_values)

Output:

Original array: [-1.          0.          1.          1.73205081]
Arctan values (in radians): [-0.78539816  0.          0.78539816  1.04719755]

Notice that arctan(sqrt(3)) gives π/3 (approximately 1.047).


Converting Radians to Degrees

Often, you'll want the result in degrees. You can easily convert the output of np.arctan using np.degrees().

python numpy arctan-图3
(图片来源网络,侵删)
import numpy as np
# Calculate arctan(1) in radians
radians = np.arctan(1)
# Convert the result to degrees
degrees = np.degrees(radians)
print(f"arctan(1) = {radians} radians")
print(f"Which is {degrees} degrees")

Output:

arctan(1) = 0.7853981633974483 radians
Which is 45.0 degrees

Visualization: Plotting the arctan Function

Seeing the function graphed is a great way to understand its behavior.

import numpy as np
import matplotlib.pyplot as plt
# Create a range of x values from -10 to 10
x = np.linspace(-10, 10, 400)
# Calculate the arctan for each x value
y = np.arctan(x)
# Create the plot
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='y = arctan(x)')
# Add labels and title'The Arctangent Function')
plt.xlabel('x')
plt.ylabel('arctan(x) in radians')
plt.grid(True)
plt.axhline(0, color='black', linewidth=0.5) # Add x-axis
plt.axvline(0, color='black', linewidth=0.5) # Add y-axis
plt.legend()
# Show the plot
plt.show()

This will generate a plot showing the classic S-shaped curve of the arctangent function, with horizontal asymptotes at y = -π/2 and y = π/2.


Important Distinction: arctan vs. arctan2

This is a crucial point that often confuses beginners. For calculating the angle of a point (x, y), you should almost always use np.arctan2.

Feature np.arctan(y / x) np.arctan2(y, x)
Purpose Calculates the angle whose tangent is y/x. Calculates the angle from the positive x-axis to the point (x, y).
Arguments One argument (the ratio y/x). Two arguments (y and x separately).
Quadrant Handling Poor. It can't distinguish between angles in opposite quadrants because the ratio y/x is the same. For example, arctan(1/1) and arctan(-1/-1) both return π/4. Excellent. It uses the signs of both x and y to determine the correct quadrant.
Division by Zero Problematic. It will raise a ZeroDivisionError if x is 0. Handles gracefully. It correctly defines arctan2(y, 0) as π/2 (if y > 0) or -π/2 (if y < 0).

Example: Why arctan2 is Better

Let's find the angle for the point (1, 1) and (-1, -1).

import numpy as np
# Point in the 1st quadrant
x1, y1 = 1, 1
angle1_arctan = np.arctan(y1 / x1)
angle1_arctan2 = np.arctan2(y1, x1)
print(f"For ({x1}, {y1}):")
print(f"  arctan(y/x) = {angle1_arctan:.4f} radians")
print(f"  arctan2(y, x) = {angle1_arctan2:.4f} radians\n")
# Point in the 3rd quadrant
x2, y2 = -1, -1
# This will fail!
# angle2_arctan = np.arctan(y2 / x2) # This gives the same result as angle1_arctan
angle2_arctan2 = np.arctan2(y2, x2)
print(f"For ({x2}, {y2}):")
print(f"  arctan(y/x) would give the same result as above!")
print(f"  arctan2(y, x) = {angle2_arctan2:.4f} radians")

Output:

For (1, 1):
  arctan(y/x) = 0.7854 radians
  arctan2(y, x) = 0.7854 radians
For (-1, -1):
  arctan(y/x) would give the same result as above!
  arctan2(y, x) = -2.3562 radians

As you can see, arctan gives the same angle for both points, which is incorrect. arctan2 correctly identifies that (1, 1) is at π/4 and (-1, -1) is at -3π/4 (or 5π/4).


Summary and When to Use Which

Function Use Case
np.arctan(x) When you have a single ratio y/x and you don't care about the original signs of y and x. This is rare in practice.
np.degrees(np.arctan(x)) When you need the arctangent of a ratio and want the result in degrees.
np.arctan2(y, x) The standard for finding angles. Use this when you have a point (x, y) and need to find the angle it makes with the positive x-axis. Essential for physics, engineering, and computer graphics (e.g., converting from Cartesian to polar coordinates).
分享:
扫描分享到社交APP
上一篇
下一篇