$ cat a.c
#include <stdio.h>
int main() {
printf("%s\n", 5056.45 + 10112.92 == 15169.37 ? "granted" : "Stop b
+laming Perl for your own mistakes!");
return 0;
}
$ gcc -o a a.c && a
Stop blaming Perl for your own mistakes!
45/100, 92/100 and 37/100 are all periodic numbers in binary just like 1/3 is in decimal. It would take infinite storage to store it accurately as a floating point number (regardless of the language). As such, there are tiny differences between the number you specify any the number you actually have
$ perl -e'printf "%.20e\n", $_ for @ARGV' 0.45 0.92 0.37
4.50000000000000011102e-01
9.20000000000000039968e-01
3.69999999999999995559e-01
That's why you must include a tolerance for error when dealing with floating points numbers.
$ perl -le 'print abs(5056.45 + 10112.92 - 15169.37) < 0.0001 ? "as ex
+pected" : "perl math sucks!"'
as expected
$ perl -le 'print sprintf("%.4f", 5056.45 + 10112.92) eq sprintf("%.4f
+", 15169.37) ? "as expected" : "perl math sucks!"'
as expected
That's 9 digits of precision, and you can even go higher.
-
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.