Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: float values and operators

by Zaxo (Archbishop)
on Aug 11, 2004 at 20:07 UTC ( [id://382074]=note: print w/replies, xml ) Need Help??


in reply to float values and operators

You're hitting a fundamental problem with representing decimal fractions in binary form. It is a limitation of your processor's floating point arithmetic which is exhibited in all languages, not just perl. You can eliminate the problem by rounding with sprintf before comparison.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: float values and operators
by hardburn (Abbot) on Aug 11, 2004 at 20:12 UTC

    That's what I thought, too, but it doesn't appear to be the case:

    $ perl -le '$a = 36.8; $b = 36.6; print "true\n" if $a >= ($b + 0.2);' # Prints nothing, just as poster showed $ perl -le '$a = 36.8; $b = 36.6; $c = $b + 0.2; print $c;' 36.8 $ perl -le '$a = 36.8; $b = 36.6; $c = $b + 0.2; print $a;' 36.8 $ perl -le '$a = 36.8; $b = 36.6; $c = $b + 0.2; print $b;' 36.6

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

      $ perl -e'print 36.8 - (36.6 + 0.2)' -7.105427357601e-15

      After Compline,
      Zaxo

        Hrm, that's what I get, too. So why doesn't the imprecision show up when you print the variables out?

        "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re^2: float values and operators
by Plankton (Vicar) on Aug 11, 2004 at 21:28 UTC
    Hi Zaxo,

    I noticed that this doesn't happen in C ...
    bash-2.05b$ cat float.c #include <stdio.h> int main () { float a = 36.8; float b = 36.6; if( a >= ( b + 0.2 ) ) { printf ("true\n"); } } bash-2.05b$ gcc -o float float.c bash-2.05b$ ./float true
    ... and does happen in Python ...
    bash-2.05b$ cat float.py #!/usr/bin/python A = 36.8 B = 36.6 if( A >= B + 0.2 ): print "true" else: print "false" bash-2.05b$ ./float.py false
    I would of included a java example but I aint got all day to download the SDK. Maybe I'll update with one later. Can you explain why C deals with float point number while Perl and Python appear to have this problem? Is it a compiled verses and interpreted language issue?

    Thanks

    Plankton: 1% Evil, 99% Hot Gas.

      Are you sure C "deals"?

      $ cat imprec.c #include <stdio.h> int main () { float fa = 36.8; float fb = 36.6; double da = 36.8; double db = 36.6; printf( ( fa >= ( fb + 0.2 ) ) ? "true\n" : "false\n" ); printf( ( da >= ( db + 0.2 ) ) ? "true\n" : "false\n" ); } $ gcc -o imprec imprec.c $ ./imprec true false

      You're seeing the result of cut-off caused by float's lower precision.

      Perl and Python use doubles in all floating point operations.

      Makeshifts last the longest.

      C doesn't deal, actually:

      $ cat a.c #include <stdio.h> int main() { printf("%s\n", 36.6 == 36.8-0.2 ? "true" : "false"); return 0; } $ gcc a.c $ a.out false
Re^2: float values and operators
by soulchild (Acolyte) on Aug 11, 2004 at 20:25 UTC
    You're right. Using sprintf to round the values before comparison does the job. Nevertheless I didn't quite understand why this is necessary. Could somebody explain this a little bit more verbose? Thanks a lot, guys!
      Recipe 2.2 in the Perl Cookbook, Second Edition is excellent reading on this subject.

      Basically, when you use a floating point number, such as 36.6, the computer doesn't store that exact value. Remember, computers are binary. When you get down to it, there's nothing more than transistors. The memory storage only really works well for integers. So the computer has to figure out some way to store approximations of the number.

      To paraphrase the cookbook, the only numbers well-representable in binary are those involving powers of two. For example, .125 is 1/8. That's exactly representable in binary notation of floating point numbers.

      However, take a number like 36.6. In fractional form, it would be 183/5, nothing to do with powers of two. The way the computer really stores the number can be seen:

      my $a = 36.6; printf "%s is %.30g\n", ($_) x 3 for $a;
      (Code shamelessly copied from the Perl Cookbook.)

      That gives us 36.600000000000001. Similarly, 36.8 is given as 36.799999999999997.

      So now you see why the comparisons failed. You weren't working with exact values.

      Perl's (and indeed, the C library's) rounding function are not exactly ``round up at five,'' but actually ``round towards even.'' So that way, sprintf will round 36.6 to an even 36.6 for calculating. So now, numerical comparisons work with nice and even numbers.

      Take a look at the Perl Cookbook on this one. It's a very good read. I've just summarised what it has written very well.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://382074]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-03-29 13:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found