Why does float() cut off trailing zeros?

微笑、不失礼 提交于 2019-12-11 03:57:02

问题


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

回答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.




回答2:


You can keep the zeros by formatting the output:

eg: if the output is 0.96,

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

Output:

'0.9600'

The output will be a string though..

The below article might be a good read: https://docs.python.org/2/tutorial/floatingpoint.html

It explains why Python displays floats in the above format.




回答3:


A floating point number is simply an approximation in python (and other programming language)...for example a decimal is computed as a binary value. It is difficult to find the exact values for most base 10 operations

After carefully reviewing this link, you will see why python does not gave exact values for your operations converted in base 2

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

using print can also do the job

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


来源:https://stackoverflow.com/questions/34302749/why-does-float-cut-off-trailing-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!