获取Python中这种浮点数的精确小数位数的近似值


要获取这种浮点数的精确小数位数的近似值,请使用 Python NumPy 中 numpy.finfo() 方法的 precision 属性。finfo() 的第一个参数是浮点数,即要获取其信息的浮点数据类型。

步骤

首先,导入所需的库:

import numpy as np

检查 float16 类型。precision 用于获取小数位数的近似值。iexp 用于获取指数部分的位数。min 是给定 dtype 的最小值。max 是给定 dtype 的最大值:

a = np.finfo(np.float16(45.976))
print("The precision to get the approximate number of decimal digits...\n",a.precision)
print("Number of bits in the exponent portion...\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("\nThe precision to get the approximate number of decimal digits...\n",a.precision)
print("Number of bits in the exponent portion...\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("\nThe precision to get the approximate number of decimal digits...\n",a.precision)
print("Number of bits in the exponent portion...\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 approximate number of decimal digits to which this kind of float is precise, use the precision attribute of the numpy.finfo() method in Python Numpy
# The first parameter of the finfo() is the float i.e. the kind of float data type to get information about.

# Checking for float16 type
a = np.finfo(np.float16(45.976))
print("The precision to get the approximate number of decimal digits...\n",a.precision)
print("Number of bits in the exponent portion...\n",a.iexp)
print("Minimum of float16 type...\n",a.min)
print("Maximum of float16 type...\n",a.max)

# Checking for float32 type
b = np.finfo(np.float32(22.3))
print("\nThe precision to get the approximate number of decimal digits...\n",a.precision)
print("Number of bits in the exponent portion...\n",b.iexp)
print("Minimum of float32 type...\n",b.min)
print("Maximum of float32 type...\n",b.max)

# Checking for float type
c = np.finfo(np.float64(29.2))
print("\nThe precision to get the approximate number of decimal digits...\n",a.precision)
print("Number of bits in the exponent portion...\n",c.iexp)
print("Minimum of float64 type...\n",c.min)
print("Maximum of float64 type...\n",c.max)

输出

The precision to get the approximate number of decimal digits...
3
Number of bits in the exponent portion...
5
Minimum of float16 type...
-65500.0
Maximum of float16 type...
65500.0

The precision to get the approximate number of decimal digits...
3
Number of bits in the exponent portion...
8
Minimum of float32 type...
-3.4028235e+38
Maximum of float32 type...
3.4028235e+38

The precision to get the approximate number of decimal digits...
3
Number of bits in the exponent portion...
11
Minimum of float64 type...
-1.7976931348623157e+308
Maximum of float64 type...
1.7976931348623157e+308

更新于:2022年2月24日

588 次浏览

开启您的职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.