Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Float loses precision?

I have a program that takes a float. The number, say, is 1353118103.108893381. The number is part of a larger string that is passed in, with each argument separated by a whitespace. For example Arg1 Arg2 1353118103.108893381 Arg3 would be the whole thing that's passed into the program. The program stores the input into a string inps. I then split each argument into a list using inps.split(' ').

So I now have something like finput = ['Arg1', 'Arg2', '1353118103.108893381', 'Arg3']. I now want to play around with the floating point number. However, the floating point number is currently a string, so I want to convert it to a floating point number type. I use rinput = float(finput[2]). However, when I do print "%.9f" % rinput, the output gives me 1353118103.108893394 (the last 2 numbers are off). Any ideas why the program does this?

Thanks!

like image 861
pauliwago Avatar asked Apr 20 '26 12:04

pauliwago


1 Answers

In a floating point representation, each bit is either used to represent the integer part, or the fraction part of the number. The bigger the integer part (in absolute value), the more bits you need in order to represent it, thus you're left with fewer bits for the fraction, thus risk losing precision.

Try storing the integer part and the fraction part separately, or use decimal

like image 133
shx2 Avatar answered Apr 23 '26 02:04

shx2