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

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: Explain floating point arithmetic result
by Corion (Patriarch) on Jun 04, 2008 at 10:15 UTC
Re: Explain floating point arithmetic result
by moritz (Cardinal) on Jun 04, 2008 at 10:14 UTC
    If you want to know what the code does, just run it, and ispect $res afterwards, for example by printing.

    If that's not your question, please try to rephrase it. See also How (Not) To Ask A Question.

    Also please the Writeup Formatting Tips, the markup here is <code>...</code>, not [code]...[/code].

Re: Explain floating point arithmetic result
by apl (Monsignor) on Jun 04, 2008 at 14:46 UTC
    You got the response you did because you said
    Can any one explain me how the result is like this instead of 5.1.

    without explaining what this is. (I'm assuming it's something like 5.1000000000001.) Corion gave you the best possible leads for your enlightenment.

    I'm curious: had you heard of floating-point (as opposed to decimal) numbers before? There's no reason you had to; usually only professional programmers know the concept. As you might tell, a lot of people ask the same type of question you did.

Re: Explain floating point arithmetic result
by starbolin (Hermit) on Jun 04, 2008 at 20:07 UTC

    Do you mean:

    perl -e 'print 5.1 + 100005.2 - 100005.2' 5.09999999997672?
    Note that this does what you expect:
    perl -e 'print 5.1 + ( 100005.2 -100005.2 )' [12:36pm] 5.1
    To summarize, the bible , most rational numbers are not representable exactly by binary numbers. When the larger constant 100005.2 is added to the smaller constant 5.1 the representational errors in the larger constant can swamp out the smaller constant.

    Re-arranging terms as I did in the second example can help. A more universal method is to insure that all constants have exact representations base 2. i.e.

    %perl -e ' printf "%f %f \n", 0x186A5, ( 5.1 + 0x186A5 ) - 0x186A5' 100005.000000 5.100000


    s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}
Re: Explain floating point arithmetic result
by sago (Scribe) on Jun 05, 2008 at 08:43 UTC

    5.10000000000582
    Is the result of the expression
Re: Explain floating point arithmetic result
by ikegami (Patriarch) on Jun 05, 2008 at 08:58 UTC
    Some specifics about the numbers you provided:
    >perl -le"printf qq{%.16e\n}, 5.1" 5.0999999999999996e+000 >perl -le"printf qq{%.16e\n}, 100005.2" 1.0000520000000000e+005

    Notice how the computer is unable to represent 5.1 exactly? Others have explained why.