Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

As previous posts have mentioned, floating point numbers are only stored in a limited precision. If your number can be written in a binary non-repeating decimal , your ok, but for repeating floating point numbers in binary way, some accuracy is lost. For example, 1/4th can be written as a binary non-repeating decimal, (1/4 = 0.01 binary), but 1/5th is repeating in binary form (1/5 = 0.00110011...) and will get truncated. This means that for a computer, 1/5 is not 0.2!

The important lesson is that you should never (I mean it!) compare floating point numbers for equality. By the way, this goes for most programming languages.

To solve your problem, write the numbers as a formatted string wide enough, and compare those. For example:

my $val1 = 17554.61 - 2194.33; my $val2 = 19748.94; my $val1_str = sprintf("12.2f", $val1); my $val2_str = sprintf("12.2f", $val2); print ("equal\n") if ($val1_str eq $val2_str);

In reply to Re: perl subtraction by lyklev
in thread perl subtraction by jagdish.eashwar

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-20 15:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found