Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

unexpected result using '>='

by jonnyfolk (Vicar)
on Aug 16, 2006 at 22:54 UTC ( #567780=perlquestion: print w/ replies, xml ) Need Help??
jonnyfolk has asked for the wisdom of the Perl Monks concerning the following question:

The following code enters the 'unless' block even though the two sides seem equal. could someone possibly explain why this is and suggest how I should express this?
#!/usr/bin/perl -w use strict; print "Content-type: text/html\n\n"; my $in = 119.8; my $in_view = $in * 2; my $count = 0; my $period = 599; while ($count < 5){ unless ($period >= $in_view) { print "$period ::$in_view<br>"; $in = $period; } $count += 1; $period = $period - $in; }

Comment on unexpected result using '>='
Download Code
Re: unexpected result using '>='
by GrandFather (Cardinal) on Aug 16, 2006 at 23:01 UTC

    Adding

    print "\n", $in_view - $period, "\n";

    after your current print line tells a story:

    Content-type: text/html 239.6 ::239.6<br> 2.8421709430404e-014 0 ::239.6<br> 239.6

    DWIM is Perl's answer to Gödel

      I see, thanks

      How can I force the calculation to calculate to 2 decimal places only - I've tried sprintf but the result is still in discrepancy.

        You could use ge rather than >= which stringises the values.

        Your original code then prints:

        Content-type: text/html 119.8 ::239.6<br>

        DWIM is Perl's answer to Gödel
        You mean something like $period - $in_view > .01 instead of $period >= $in_view?

        By the way, it's just a matter of time till you burn yourself by misinterpreting the sense of an unless. Some people recommend never using unless; I think it's ok so long as the expression is a single simple variable.

Re: unexpected result using '>='
by ysth (Canon) on Aug 16, 2006 at 23:42 UTC
    Because we use base 10, not base 2, floating point numbers have a non-integral number of digits of precision. When showing them as strings, the next lower number of digits of precision is used, and what you see is slightly rounded. So $period and $in_view can be not quite equal and still stringify to the same thing.

    This is generally regarded as a good thing, since people don't expect print .1 to produce "0.10000000000000001" instead of ".1".

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://567780]
Approved by Paladin
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2014-07-14 01:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (253 votes), past polls