Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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; }

Replies are listed 'Best First'.
Re: unexpected result using '>='
by GrandFather (Sage) on Aug 16, 2006 at 23:01 UTC


    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 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.

        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
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://567780]
Approved by Paladin
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2018-02-22 21:37 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (299 votes). Check out past polls.