为什么float()会切断尾随零?

时间:2015-12-16 01:56:30

标签: python math floating-point numbers decimal

代码成功地将一个包含多个数字的大文件裁剪成几个带有数字的较小文本文件,但它会产生一个有趣的怪癖。

所有数字应该是两个小数点,如2.7400,但它们打印为2.74。

以下是文件的片段

0.96
0.53
0.70
0.53
0.88
0.97

为什么会这样?有没有办法解决这个或这只是一个漂浮的浮动()?

from itertools import islice

def number_difference(iterable):
    return float(iterable[-1].strip('\n')) - float(iterable[0].strip('\n'))

def file_crop(big_fname, chunk_fname, no_lines):
    with open(big_fname, 'r') as big_file:
        big_file.readline()
        ifile = 0
        while True:
            data = list(islice(big_file, no_lines))
            if not data:
                break
            with open('{}_{}.locs'.format(chunk_fname, ifile), 'w') as small_file:
                offset = int(float(data[0].strip('\n')))
    map(lambda x: str(float(x.strip('\n')) - offset) + '\n', data)
    small_file.write('{} {} L\n'.format(len(data), number_difference(data)))
        small_file.write(''.join(map(lambda x: str(round((float(x.strip('\n')) - offset),4)) + '\n', data)))
            ifile += 1

3 个答案:

答案 0 :(得分:3)

您可以通过格式化输出来保留零:

例如:如果输出为0.96,

x= 0.96
"{0:.4f}".format(x)

输出:

'0.9600'

输出将是一个字符串..

以下文章可能是一个很好的阅读: https://docs.python.org/2/tutorial/floatingpoint.html

它解释了为什么Python以上述格式显示浮点数。

答案 1 :(得分:2)

IEEE 754浮点数(其中floatbinary64)并非设计用于保存精度信息。如果您需要这样做,那么您应该使用decimal.Decimal代替。

>>> decimal.Decimal('0.70')
Decimal('0.70')
>>> print decimal.Decimal('0.70')
0.70

有关详细信息,请参阅decimal documentation

答案 2 :(得分:0)

浮点数只是python(和其他编程语言)中的近似值...例如,十进制数被计算为二进制值。很难找到大多数基础10操作的确切值

仔细查看此链接后,您将看到为什么python没有为您在base 2中转换的操作提供准确值

https://docs.python.org/2/tutorial/floatingpoint.html

使用print也可以完成这项工作

print("%.4f" % 0.96) or
whatever_file.write("%.4f" % 0.96)