【发布时间】:2016-03-22 01:00:28
【问题描述】:
该代码成功地将一个包含许多数字的大文件裁剪为几个带有数字的较小文本文件,但它产生了一个有趣的怪癖。
所有数字都应保留四位小数,如 2.7400,但它们打印为 2.74。
这是来自文件的 sn-p
0.96
0.53
0.70
0.53
0.88
0.97
为什么会这样?有没有办法解决这个问题,或者这只是 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
【问题讨论】:
-
2.74 和 2.7400 的
float表示是相同的。在转换为float后,无法知道在原始字符串表示中使用了多少额外的无关零。 -
A
float代表一个数字,尾随零不是数字的属性。 2.74 = 2.7400。
标签: python math floating-point numbers decimal