[英]Why does float() cut off trailing zeros?
該代碼成功地將一個包含許多數字的大文件裁剪為幾個帶有數字的較小文本文件,但它產生了一個有趣的怪癖。
所有數字都應該是小數點后四位,例如 2.7400,但它們打印為 2.74。
這是一個文件的片段
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
您可以通過格式化輸出來保留零:
例如:如果輸出為 0.96,
x= 0.96
"{0:.4f}".format(x)
IEEE 754 浮點數(其中
float<\/code>是
binary64<\/a> )並非旨在保存精度信息。
如果你需要這樣做,那么你應該使用
decimal.Decimal<\/code>代替。
>>> decimal.Decimal('0.70')
Decimal('0.70')
>>> print decimal.Decimal('0.70')
0.70
浮點數只是python(和其他編程語言)中的近似值......例如,小數被計算為二進制值。 很難找到大多數以 10 為底的操作的確切值
仔細查看此鏈接后,您會明白為什么 python 沒有為您的以 2 為基數轉換的操作提供准確的值
https://docs.python.org/2/tutorial/floatingpoint.html
使用 print 也可以完成這項工作
print("%.4f" % 0.96) or
whatever_file.write("%.4f" % 0.96)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.