python中如何将二進制轉為十進制?在 Python 中,我們使用函數獲取數字的絕對值abs()但abs()可以做的遠不止這些此函數還可以處理不太常見的值,今天小編就來聊一聊關于python中如何将二進制轉為十進制?接下來我們就一起去研究一下吧!
在 Python 中,我們使用函數獲取數字的絕對值abs()。但abs()可以做的遠不止這些。此函數還可以處理不太常見的值。
Python 中複數的絕對值當我們使用abs()處理複數時,該函數返回複數的大小。
complexA = 2 1j * 3
complexB = (2 - 1j) * 3
# Output magnitude of complex numbers
print("Absolute values of", complexA, "and", complexB, "are:")
print(abs(complexA), " | ", abs(complexB))
輸出:
Absolute values of (2 3j) and (6-3j) are:
3.605551275463989 | 6.708203932499369
我們大多數情況下使用abs()函數求十進制數的絕對值。處理二進制數、八進制數、十六進制數時,返回什麼結果呢?
positiveBinary = 0b11110
negativeBinary = -0b11110
print("Absolute value of 30 and -30 in binary form:")
print(abs(positiveBinary), " | ", abs(negativeBinary))
輸出:
Absolute value of 30 and -30 in binary form:
30 | 30
positiveHex = 0x1E
negativeHex = -0x1E
print("Absolute value of 30 and -30 in hexadecimal form:")
print(abs(positiveHex), " | ", abs(negativeHex))
輸出:
Absolute value of 30 and -30 in hexadecimal form:
30 | 30
positiveOctal = 0o36
negativeOctal = -0o36
print("Absolute value of 30 and -30 in octal form:")
print(abs(positiveOctal), " | ", abs(negativeOctal))
輸出:
Absolute value of 30 and -30 in octal form:
30 | 30
不論什麼進制,都是返回十進制值。
科學記數法的絕對值當我們使用abs()函數對用科學記數法的數求絕對值,我們會得到一個常規的浮點值。
positiveExp = 3.0e1
negativeExp = -3.0e1
print("Absolute value of 30 and -30 in scientific notation:")
print(abs(negativeExp), " | ", abs(negativeExp))
輸出:
Absolute value of 30 and -30 in scientific notation:
30.0 | 30.0
# Store some uncommon values in variables
positiveInf = float("inf")
negativeInf = float("-inf")
nanValue = float("nan")
# Output their absolute values
print("Absolute values of:")
print("Positive infinity ( ∞):", abs(positiveInf))
print("Negative infinity (-∞):", abs(negativeInf))
print("Not a number (NaN):", abs(nanValue))
abs()函數如何處理兩種特殊值:正無窮大和負無窮大以及非數字值 (NaN)。
輸出:
Absolute values of:
Positive infinity ( ∞): inf
Negative infinity (-∞): inf
Not a number (NaN): nan
更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!