0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

#0173(2025/06/18)`np.arctan()` と `np.arctan2()` の違い

Posted at

np.arctan()np.arctan2() の違い

はじめに

数値計算やロボット・画像処理などで「角度」を扱う場面は多々あります。その際、np.arctan()np.arctan2() のどちらを使うべきかで迷った経験はありませんか?本記事では 象限情報が必要かどうか を軸に、両者の違いと選び方を実践的にまとめます。


結論早見表

  • 片方の値しかなく、±90° 以内で十分np.arctan()
  • 2D ベクトルの完全な向き(0°〜360°)が欲しいnp.arctan2()
  • x が 0 になる可能性がある → 迷わず np.arctan2()

1. np.arctan() の基礎

  • シグネチャ: np.arctan(x)
  • 引数: 比 y/x(実数)を 1 つ渡す
  • 戻り値の範囲: $-\frac{\pi}{2},;\frac{\pi}{2}$(−90°〜+90°)
  • 用途: 勾配や単純な傾きを取りたいとき

ポイント: x の符号情報が欠落するため、(−1,−1) と (1,1) の区別がつかない。


2. np.arctan2() の基礎

  • シグネチャ: np.arctan2(y, x)
  • 引数: ベクトルの $y$, $x$ を別々に渡す
  • 戻り値の範囲: (-\pi,;\pi](−180°〜+180°)
  • 用途: ロボットのヨー角、方位角、回転行列↔オイラー角変換など
  • メリット: x と y の符号を見て象限を判定。x=0 でも安全。

3. コード例で違いを体感

import numpy as np

# 4 つのベクトル (x, y)
x = np.array([-1, -1,  1, 1])
y = np.array([-1,  1, -1, 1])

# arctan は y/x を直接渡す
theta_atan  = np.degrees(np.arctan(y / x))
# arctan2 は (y, x) を渡す
theta_atan2 = np.degrees(np.arctan2(y, x))

print(theta_atan)   # [-45. -45. -45.  45.]
print(theta_atan2)  # [-135.  135.  -45.   45.]

出力解説

  • arctan は全て ±45°。象限情報が失われています。
  • arctan2 は左下を −135°、左上を +135° と正しく判定します。

4. よくある落とし穴

  • ゼロ割り: y/x で x=0 のケース → arctan2 を使う
  • 180° と −180° の扱い: arctan2 は範囲が (−π, π] なので、必要に応じて 0〜360° に正規化しましょう。
theta = np.degrees(np.arctan2(y, x))
angle360 = (theta + 360) % 360  # 0〜360° に変換

5. 現場シナリオ別の選択ガイド

ロボット/ドローンの姿勢推定

  • 必須情報: 機体がどの象限を向いているか → arctan2

画像処理でのエッジ方向解析

  • 勾配ベクトルの向き(0〜360°)が必要 → arctan2

線形回帰の傾きチェック

  • 傾き tanθ を arctan で直接角度へ → arctan

6. まとめ

  • 象限を意識しない 一変数の逆正接 → np.arctan()
  • 象限を意識した 2D 角度計算 → np.arctan2()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?