0

First of all, I already know that :

  • 3.001 and 6.001 don't have an exact binary representation.
  • 3.001 <> 6.001 from a "floating point of view".

Now let's consider the following code.

for val in ["3 + 3.001", "6.001"]:
    d = eval(val)

    print("\nCODE    :", val)
    print("DEFAULT :", d)

    for prec in [16, 20]:
        message = "{" + "0:.{0}f".format(prec) + "}"
        print(
            "{0}: {1}".format(
                message,
                message.format(d)
            )
        )

This prints :

CODE    : 3 + 3.001
DEFAULT : 6.0009999999999994
{0:.16f}: 6.0009999999999994
{0:.20f}: 6.00099999999999944578

CODE    : 6.001
DEFAULT : 6.001
{0:.16f}: 6.0010000000000003
{0:.20f}: 6.00100000000000033396

We can see that 3 + 3.001 seems to be printed by default using 16 digits and rounding. But for 6.001 it seems that at most 15 digits are used before rounding.

Why ?

projetmbc
  • 1,332
  • 11
  • 26
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – DeepSpace Jun 01 '17 at 14:42
  • Because `3 + 3.001` is not `6.001` in binary floating-point arithmetic. Try printing the _exact_ internal representation using `float(3.001).as_integer_ratio()` and see that it's different for `3.001` and `6.001`. – yeputons Jun 01 '17 at 14:48
  • @yeputons My problem us not there. The problem for is to understand why Python don't use the same method to print this two different floats. – projetmbc Jun 01 '17 at 14:51
  • @DeepSpace. This is definitely not a dupe, at least not the question you marked. OP makes that pretty clear. – Mad Physicist Jun 01 '17 at 14:53
  • @projetmbc in that case I'd recommend to seriously truncate your question and leave only two hard-coded numbers and then ask how Python chooses what to print. Right now it looks like the question is about "why `3 + 3.001` and `6.001` are printed differently", and the answer is "because these are two different numbers because of floating point computations". Something like "why X/Y is rounded and printed, but X1/Y1 is rounded the different way" would be a better question, I think. – yeputons Jun 01 '17 at 19:11
  • I have tried to clarify my question. – projetmbc Jun 02 '17 at 12:16
  • @DeepSpace Not a duplicate. – projetmbc Jun 02 '17 at 12:16

0 Answers0