I am trying to carry out a simple comparison of two numbers in Perl, but I have encountered some interesting results. If someone could point me to a foolish mistake somewhere I would be more than grateful!

I understand that eq carries out a string comparison, whereas == carries out a numerical comparison, however when I try to compare numbers after a simple arithmetic calculation == returns false when I would expect true, while eq returns true correctly.

$num1 = 523.20; $num2 = 23.2; $eq = 500; print ("$num1, $num2, ($eq, ". ($num1 - $num2) ."), ". ($n +um1 - $num2 eq $eq) .", ". (($num1 - $num2) == $eq). ".\n");

prints

523.2,    23.2,    (500,    500),    1,    .

I have come to the conclusion that this is because of floating point arithmetic (correct me if I'm wrong), as printing $num1 - $num2 yeilds a value of 1.13686837721616e-13.

My confusion comes because if I alter the above script from 23.2 to 0.2, the result for == is true (correctly), and I can't understand where the difference lies that should cause == to deviate in such a manner.

Of course the ultimate question is: is there something I'm doing (or not doing) which can account for this? Is there a better way of doing this simple comparison which will yield consistent results?


In reply to eq vs == by spikeheap

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.