如何在Python中添加浮点数后得到精确的结果?

时间:2015-03-24 17:23:46

标签: python

给出一个腌制文件 - log.dat ,其中包含 字符串列表 。我写了一个pythonic函数,它读取文件并查找表格的一行,

Xerror: 0.xxxx

每当遇到这样的行时,我必须提取 浮点值 并计算这些错误值的总和。当我到达 EOF 时,我需要打印此类错误行的总数和错误值的平均值。

的log.dat

Xerror: 0.2395
0.00001000ems
Xerror: 0.2785
ggn0.000990909
Xerror: 0.2567
xsddtd0.98789
Xerror: 0.2245
Xerror: 0.2000
Xerror: 0.2563

Pythonic计划:

from __future__ import print_function
import os
textFile = "page06.txt"

if os.path.isfile(textFile):
    ln = find = 0
    total = 0.0000

    fileobj = open(textFile)
    while True:
        line = fileobj.readline()
        if not line:
            break
        else:
            print(line , end="")
            ln += 1
            substring = "Xerror:"
            flag = substring in line

            if flag:
                find += 1


                length = len(line)
                index = line.index(".")
                result = line[index:length]
                num = float(result)
                total = total + num                  

    print()
    print("Total Lines: %d" %ln)
    print("Total Lines which represent error: %d" %find)
    print("Total sum of floating-point numbers: %f" %total)
    fileobj.close()
else:
    print ("File does not exist")

在从文件

中提取和添加这些内容之后,我没有得到我的要求的确切精确度
0.2395 + 0.2785 + 0.2567 +  0.2245 + 0.2000 + 0.2563

我将如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

将%f格式更改为%.4f。这将输出4个十进制数字的答案,这是您的所有数据集保证。

答案 1 :(得分:2)

您可以使用decimal模块。不要将数字转换为浮点数,而是

import decimal
... 
    total = decimal.Decimal(0)
    ...
        num = decimal.Decimal(result)