當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python math.atan2()用法及代碼示例


Python math.atan2() 方法

math.atan2() 方法是 math 模塊的一個庫方法,用於獲取 "y/x" 的反正切值(即 atan(y/x)),它接受兩個數字並返回 "y/x" 的反正切值。

注意: math.atan2() 方法接受唯一的數字,如果我們提供除數字以外的任何其他內容,則返回錯誤 TypeError -“TypeError:a float is required”。

math.atan2() 方法的語法:

    math.atan2(y, x)

參數: y, x– 是要計算其反正切的數字(即atan(y/x))。

返回值: float– 它返回一個浮點值,它是數字的反正切值y/x

例:

    Input:
    y = 0.2345
    x = 1.234

    # function call
    print(math.atan2(y, x))

    Output:
    0.18779323183177443

用於演示 math.atan2() 方法示例的 Python 代碼

# python code to demonstrate example of 
# math.atan2() method 

# importing math module
import math

# numbers
x = -1
y = 1
print("atan2(",x,",",y,") is = ", math.atan2(x,y))

x = 0.2345
y = 1.234
print("atan2(",x,",",y,") is = ", math.atan2(x,y))

x = -5
y = 5
print("atan2(",x,",",y,") is = ", math.atan2(x,y))

x = 10
y = 20.23
print("atan2(",x,",",y,") is = ", math.atan2(x,y))

輸出

atan2( -1 , 1 ) is =  -0.7853981633974483
atan2( 0.2345 , 1.234 ) is =  0.18779323183177443
atan2( -5 , 5 ) is =  -0.7853981633974483
atan2( 10 , 20.23 ) is =  0.45908957477179374

類型錯誤示例

# python code to demonstrate example of 
# math.atan2() method with an exception

# importing math module
import math

# numbers
x = "2"
y = "34"
print("atan2(",x,",",y,") is = ", math.atan2(x,y))

輸出

Traceback (most recent call last):
  File "/home/main.py", line 10, in <module>
    print("atan2(",x,",",y,") is = ", math.atan2(x,y))
TypeError:a float is required


相關用法


注:本文由純淨天空篩選整理自 math.atan2() method with example in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。