3

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!

pauliwago
  • 6,373
  • 11
  • 42
  • 52
  • 3
    [Floating point numbers are not exact by definition.](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) – beatgammit Mar 07 '13 at 06:15
  • 2
    float conversion will not run well if the digit exceed the limitation on your system. see http://docs.python.org/2/library/sys.html#sys.float_info – Thai Tran Mar 07 '13 at 06:18
  • So are you saying there's no way to implement this? Is there another way besides using float conversion? – pauliwago Mar 07 '13 at 06:19
  • 1
    @pauliwago Given that the most accurate measurement of a physical constant (the Rydberg constant) is only accurate to 13 digits, does it really matter that you only have 16-17 digits instead of 19? – Jeffrey Sax Mar 07 '13 at 06:24
  • I guess you're right. Thank you! – pauliwago Mar 07 '13 at 06:27
  • @pauliwago every built in data type has its limitation. That 's why we need numpy or bigfloat – Thai Tran Mar 07 '13 at 06:38

1 Answers1

3

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

shx2
  • 61,779
  • 13
  • 130
  • 153
  • Storing the integer part and the fracion part separately, and compute them separately is a good solution. I found another, convert the decimal number in an int/long number (multiplify pow(10,n)) and do the ope, after doing ope apply decimal dot in the right position. I did the next code which allows sum, subs and multiplications without lossing precission. You can compute with infinite decimals... https://github.com/sh1l0n/pyfloats – g4s0l1n Dec 23 '20 at 11:00