Python fabs()方法示例| Python數學函數
Python fabs()是一個內置的數學函數,用於獲取數字的絕對值。它首先找到絕對值,然後將數字轉換為浮點型數字,而不管給定的數字是整數還是浮點型。 fabs()方法位於Python中的數學庫下,這意味著我們必須首先導入數學才能使用此方法。
Python fabs()方法
內容概述
- 1 Python fabs()方法
- 2 Python中fabs()和abs()之間的區別
- 3結論
- 4另請參見
Python fabs()函數是Math函數之一,該函數返回特定表達式或特定數字的絕對值((正值))。
句法
math.fabs(number)
fabs()方法採用一個參數,即將返回其絕對值的數字。
number:可以是您要在Python中找到絕對值的數字或有效的數字表達式。
- 如果number參數為正數或負數,則fabs()函數將返回絕對值。
- 如果數字參數不是數字,則fabs()函數將返回TypeError。
返回值
該方法返回給定數字的絕對值,並以浮點型返回。
編程範例
import math # Take two integer from user num1 = float(input("Enter a float number: ")) num2 = int(input("Enter an integer: ")) # Now we will check what happens when we call fabs() print("Absolute value of float number is: ", math.fabs(num1)) print("Absolute value of integer is: ", math.fabs(num2)) # Sum of these two number sum1 = num1+float(num2) # Printing sum and absolute sum print("Sum is: ", sum1) print("Absolute value of sum is: ", math.fabs(sum1))
輸出量
Enter a float number: -26.4 Enter an integer: 12 Absolute value of float number is: 26.4 Absolute value of integer is: 12.0 Sum is: -14.399999999999999 Absolute value of sum is: 14.399999999999999
在上面的程序中,我們採用了兩個輸入,一個是浮點數(負),另一個是正整數。然後我們列印了它們的絕對值。
在這裡我們可以看到整數(12)轉換為浮點型數字。之後,我們計算了這兩個數字的和。為此,我們首先將整數轉換為浮點數。
最後,我們列印了總和的絕對值。
例子2
請參閱以下編程。
# app.py import math Tup = (11, 21, 30, -46, 19) # Tuple Declaration Lis = [-11, 22, -3.3, -44, 55] # List Declaration print('Absolute value of Positive Number = %.2f' % math.fabs(10)) print('Absolute value of Negative Number = %.2f' % math.fabs(-15)) print('Absolute value of Tuple Item = %.2f' % math.fabs(Tup[3])) print('Absolute value of List Item = %.2f' % math.fabs(Lis[2])) print('Absolute value of Multiple Number = %.2f' % math.fabs(10 + 20 - 40)) print('Absolute value of String Number = ', math.fabs('AppDividend'))
輸出量
python3 app.py Absolute value of Positive Number = 11.00 Absolute value of Negative Number = 19.00 Absolute value of Tuple Item = 46.00 Absolute value of List Item = 3.30 Absolute value of Multiple Number = 10.00 Traceback (most recent call last): File "app.py", line 13, inprint('Absolute value of String Number = ', math.fabs('AppDividend')) TypeError: must be real number, not str
在上面的示例中,我們使用了字元串,元組和列表。
對於字元串,它返回TypeError,因為我們需要一個作為整數的參數。
Python中fabs()和abs()之間的區別
Abs()和fabs()函數均用於查找數字的絕對值。兩者都將返回數字的絕對值。
區別在於,即使參數為整數,math.fabs(number)也會始終返回浮點數。相反,Python abs()將根據參數返回浮點數或整數。
如果參數是複數,則abs()將返回幅度部分,而fabs()將返回錯誤。
結論
即使自變數是整數,Python math.fabs(number)也會始終返回浮點數,如果您傳遞複數或其他數字,則它將返回錯誤。
也可以看看
Python數學copysign()
Python數學函數
Python math.sqrt()
Python math.floor()