獲取 Python 中浮點表示中指數部分的位數


要在 Python Numpy 中獲取浮點表示中指數部分的位數,請使用 numpy.finfo() 方法的 iexp 屬性。第一個引數是 float,即要獲取其資訊的浮點資料型別。

步驟

首先,匯入所需的庫 −

import numpy as np

檢查 float16 型別。iexp 用於獲取指數部分的位數。min 是給定 dtype 的最小值。max 是給定 dtype 的最小值。 −

a = np.finfo(np.float16(45.9))
print("Number of bits in the exponent portion float16 type...\n",a.iexp)
print("Minimum of float16 type...\n",a.min)
print("Maximum of float16 type...\n",a.max)

使用例項檢查 float32 型別 −

b = np.finfo(np.float32(22.3))
print("\nNumber of bits in the exponent portion float32 type...\n",b.iexp)
print("Minimum of float32 type...\n",b.min)
print("Maximum of float32 type...\n",b.max)

使用例項檢查 float 型別 −

c = np.finfo(np.float64(29.2))
print("\nNumber of bits in the exponent portion float64 type...\n",c.iexp)
print("Minimum of float64 type...\n",c.min)
print("Maximum of float64 type...\n",c.max)

例項

import numpy as np

# To get the number of bits in the exponent portion of the floating point representation, use the iexp attribute of the numpy.finfo() method in Python Numpy
# The first parameter is the float i.e. the kind of float data type to get information about.

# Checking for float16 type
# The iexp is to get the number of bits in the exponent portion
# The min is the minimum value of given dtype.
# The max is the minimum value of given dtype.
a = np.finfo(np.float16(45.9))
print("Number of bits in the exponent portion float16 type...\n",a.iexp)
print("Minimum of float16 type...\n",a.min)
print("Maximum of float16 type...\n",a.max)

# Checking for float32 type with instances
b = np.finfo(np.float32(22.3))
print("\nNumber of bits in the exponent portion float32 type...\n",b.iexp)
print("Minimum of float32 type...\n",b.min)
print("Maximum of float32 type...\n",b.max)

# Checking for float type with instances
c = np.finfo(np.float64(29.2))
print("\nNumber of bits in the exponent portion float64 type...\n",c.iexp)
print("Minimum of float64 type...\n",c.min)
print("Maximum of float64 type...\n",c.max)

輸出

Number of bits in the exponent portion float16 type...
5
Minimum of float16 type...
-65500.0
Maximum of float16 type...
65500.0

Number of bits in the exponent portion float32 type...
8
Minimum of float32 type...
-3.4028235e+38
Maximum of float32 type...
3.4028235e+38

Number of bits in the exponent portion float64 type...
11
Minimum of float64 type...
-1.7976931348623157e+308
Maximum of float64 type...
1.7976931348623157e+308

更新於: 2022-02-24

512 次瀏覽

啟程您的職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.