为什么float()切断尾随零? [英] Why does float() cut off trailing zeros?

查看:163
本文介绍了为什么float()切断尾随零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码成功地将一个包含数字的很多数字的大文件剪切成几个较小的文本文件,但是它产生了一个有趣的怪癖。

所有的数字应该是四位数点2.7400,而是打印2.74。



这是一个文件的片段

  0.96 
0.53
0.70
0.53
0.88
0.97

为什么会发生这种情况?有没有办法解决这个或这只是一个怪胎()?

  from itertools import islice 

def number_difference(iterable):
返回float(iterable [-1] .strip('\\\
')) - float(iterable [0] .strip('\\\
'))
$ b $ def file_crop(big_fname,chunk_fname,no_lines):
with open(big_fname,'r')as big_file:
big_file.readline()
ifile = 0
而真:
data = list(islice(big_file,no_lines))
如果不是数据:
打开('{} _ {}。locs')打破
。 format(chunk_fname,ifile),'w')as small_file:
offset = int(float(data [0] .strip('\\\
')))
map(lambda x:str float(x.strip('\ n')) - offset)+'\ n',data)
small_file.write('{} {} L \\\
'.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


解决方案

IEEE 754浮点数(其中 float binary64 )并不是为保存精确信息而设计的。如果您需要这样做,那么您应该使用 decimal.Decimal 来代替。

 >>> decimal.Decimal('0.70')
十进制('0.70')
>>> print decimal.Decimal('0.70')
0.70

请参阅 decimal 文档了解详细信息。


The code successfully crops a large file of many numbers to several smaller text files with number, but it produces an interesting quirk.

All numbers should be to four decimal points like 2.7400 but instead they print as 2.74.

Here is a snippet from a file

0.96
0.53
0.70
0.53
0.88
0.97

Why does this happen? Is there a way to fix this or this just a quirk of float()?

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

解决方案

IEEE 754 floating point numbers (of which float is binary64) are not designed to hold precision information. If you need to do so then you should use decimal.Decimal instead.

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

See the decimal documentation for full details.

这篇关于为什么float()切断尾随零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆