How to get the precise result after adding floating point numbers in Python?

Given a pickled file - log.dat, containing list of strings. I wrote a pythonic function that reads the file and looks for a line of the form,

Xerror: 0.xxxx

Whenever such line is encountered, I have to extract the floating-point value and compute the total of these error values. When i reach the EOF, i need to print the total number of such error lines and average of error value.

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 program:

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")

I am not getting the exact precise which my requirement is after extracting and adding these from the file

0.2395 + 0.2785 + 0.2567 +  0.2245 + 0.2000 + 0.2563

How will I achieve this?

Upvotes: 0

Views: 164

Answers (2)

user206545
user206545

Reputation:

Change the %f format to %.4f. This will output the answer with 4 decimal digits which is all your data set warrants.

Upvotes: 3

Julien Spronck
Julien Spronck

Reputation: 15423

You can use the decimal module. Instead of converting the numbers to float, you do

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

Upvotes: 2

Related Questions