【问题标题】:formatted float output with dtype precision具有 dtype 精度的格式化浮点输出
【发布时间】:2017-01-31 17:46:02
【问题描述】:

我有几个具有不同数据类型的 numpy 浮点数组。我现在想print 他们并在输出中准确包含“正确”的位数。像

这样的幼稚方法
import numpy as np

a = np.array([1.0 / 3.0], dtype=np.float64)
print(a)
print('%f' % a[0])

b = np.array([1.0 / 3.0], dtype=np.float16)
print(b)
print('%f' % b[0])

打印

[ 0.33333333]
0.333333
[ 0.33325195]
0.333252

这不是我想要的。我可以修改格式字符串 à la %.18f,但是如何将位数调整为 dtype

【问题讨论】:

    标签: python numpy floating-point format


    【解决方案1】:

    对于 NumPy 浮点数据类型,尾数长度为 in the documenation。 有了这个,就可以去

    def dtype_digits(dt):
        if dt == numpy.float16:
            mantissa = 10
        elif dt == numpy.float32:
            mantissa = 23
        elif dt == numpy.float64:
            mantissa = 52
        else:
            raise RuntimeError('Unknown float type')
        significant_digits = mantissa * numpy.log(2) / numpy.log(10)
        return int(significant_digits)
    

    然后像这样使用

    # data = numpy.array(...)
    #
    fmt = '%%.%de' % dtype_digits(data.dtype)
    for x in data:
        print(fmt % x)
    

    【讨论】:

      【解决方案2】:

      Python 的内置 repr() 就是为此目的而设计的:

      print('%r' % a[0])
      0.33333333333333331
      
      print('%r' % b[0])
      0.33325
      

      【讨论】:

        猜你喜欢
        • 2017-05-20
        • 1970-01-01
        • 1970-01-01
        • 2014-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多