oseeliger has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm pretty confused about these 4 statements ( or I'm just a blockhead in understanding the evaluation order / precedence of operators and parentheses ).

The first and third statement print a simple arithmetic opertation (using differently placed parentheses) in a float value interpreted sprintf instruction. That is ok.

But why does the second and fourth statement print different rounded values? I have no clue and don't know how to find out.

Please, could someone advise?

perl -e 'print sprintf( "%f", 66.5 * ( ( 100 + 19 ) / 100 ) ), "\n +79.135000"' perl -e 'print sprintf( "%.2f", 66.5 * ( ( 100 + 19 ) / 100 ) ), " < +-- wrong, expected 79.14\n"' perl -e 'print sprintf( "%f", 66.5 * ( 100 + 19 ) / 100 ), "\n +79.135000"' perl -e 'print sprintf( "%.2f", 66.5 * ( 100 + 19 ) / 100 ), " < +-- ok = 79.14\n"'

Replies are listed 'Best First'.
Re: strange sprintf behavior?
by Anonymous Monk on Oct 15, 2010 at 12:59 UTC
Re: strange sprintf behavior?
by TomDLux (Vicar) on Oct 15, 2010 at 14:27 UTC

    Your decimal brain tells you something divided by a hundred can be exactly represented, but in binary, 1/5, 1/10, 1/100 are infinitely repeating fractions.

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Re: strange sprintf behavior?
by ig (Vicar) on Oct 15, 2010 at 16:01 UTC
    print sprintf( "%.30f", 66.5 * ( ( 100 + 19 ) / 100 ) ), "\n79.135 +000"; print sprintf( "%.2f", 66.5 * ( ( 100 + 19 ) / 100 ) ), " <-- wrong, + expected 79.14\n"; ; print sprintf( "%.30f", 66.5 * ( 100 + 19 ) / 100 ), "\n79.135 +000"; print sprintf( "%.2f", 66.5 * ( 100 + 19 ) / 100 ), " <-- ok = 7 +9.14\n";

    produces:

    79.134999999999990905052982270718 79.13500079.13 <-- wrong, expected 79.14 79.135000000000005115907697472721 79.13500079.14 <-- ok = 79.14

    Which may make the difference more obvious.

    update: deleted incorrect example about integer Vs floating point calculations.

      Thank you all very much. It's now clearer and I think I understood it.

      The links are very informative.