On 9/2/2010 8:53 AM, Paul Johnson wrote:
On Thu, Sep 02, 2010 at 01:11:07AM +0200, Dr.Ruud wrote:
On 2010-09-02 00:49, Paul Johnson wrote:
When you want to compare floating point numbers, check that their
difference is less than some appropriately small delta:
$delta = 1e-8;
if (abs($a - $b)< $delta) # numbers are "equal"
Why call it delta when you can call it epsilon?
;)
You're absolutely right. And see Test::Number::Delta on CPAN for an
easier way of doing this in tests.
It also has no 'my', why is that?
Because it is a short snippet of code designed to show one principle.
Adding "my" would not have contributed to that goal. I was also
expecting someone to pick me up on using $a and $b. Perhaps they still
will. The answer would be very similar.
And OP should read at least one of these:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
http://en.wikipedia.org/wiki/Floating_point
http://hal.archives-ouvertes.fr/docs/00/28/14/29/PDF/floating-point-article.pdf
Yes, this is a well understood problem that nevertheless manages to
perplex many beginning programmers.
It's really not a question of it being perplexing more so than like I
said maddening in terms of why solutions just aren't intrinsic to the
programming language. If ops are slower, so what... throw some more hw
at the problem... hw is cheap... people's time isn't.
I was hoping I'd see some answer like... oh yeah... perl is smart enough
to handle that for you if you are willing to accept a performance hit...
just turn on so-and-so directive and perl will perform in non-floating
point mode and return precise answers up to some level of precision...
just like your calculator. I undertand there are modules that will help,
but it sounds like those involve significant coding changes. Or like
others suggest, convert everything to cents or fractions of cents and
then divide at the end... requires a lot of foresight or backtracking.
perl already does smart things like garbage collection, so I don't have
to think about things like malloc and free... very nice. I figured there
would be some similar perl-specific solution.
And like I mentioned, for the most part a final %.2f I believe will
handle the problem, unless you are combining *lots* of numbers with fp
error. The problem I really dislike is the final -0.00. When the answer
due to fp error is slightly less than 0.00. Putting some check on that
whenever real numbers are added is a drag.
But thanks again for all the feedback.
Jim
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/