Reg- Floating point variables

Discussion in 'Perl Misc' started by Nithy, Nov 12, 2007.

  1. Nithy

    Nithy Guest

    Hi,
    Can anyone help me in floating point round off error. I have the
    code as shown below.

    #!/usr/bin/perl
    #This program increments the value from x.1 to x.9

    $count = 0;
    $out = 0;
    while($out == 0)
    {
    print ("count = ",$count,"\n");
    $count=$count + 0.1;
    if ($count == 0.9)
    {
    $out=1;
    }

    If I run this code, it doesn't terminate when $count reach 0.9. Its
    keep on increasing. And after 5.9 its showing 5.99999999999999 & so
    on..
    But If I limits it within 0.8(if $count = 0.1 - 0.7), it gives the
    proper output. Why is it so?

    Please let me know your suggestion.

    Thanks in advance.

    Regards,
    Nithy
     
    Nithy, Nov 12, 2007
    #1
    1. Advertisements

  2. Nithy

    smallpond Guest



    Never try to test for exactly equal to a floating point number.
    It doesn't work. Floating point numbers are approximate.
    Change your code to
    if ($count >= 0.9)
    --S
     
    smallpond, Nov 12, 2007
    #2
    1. Advertisements

  3. You must have missed "Basics of Computer Numerics":
    Thou shalt not test for equal on floating point numbers

    'perldoc -q 999' gives a very brief introduction of why using floating point
    numbers has it quirks in Perl, too, just like in any other standard
    programming language.

    jue
     
    Jürgen Exner, Nov 12, 2007
    #3
  4. for my $i ( 1 .. 9 ) {
    $x += $i/10;
    }
    perldoc -q 999

    Sinan
     
    A. Sinan Unur, Nov 12, 2007
    #4
  5. Nithy

    Nithy Guest

    Thanks Sherm..
     
    Nithy, Nov 13, 2007
    #5
  6. Nithy

    Nithy Guest

    Thanks Sinan..
     
    Nithy, Nov 13, 2007
    #6
  7. Nithy

    Nithy Guest

    Thanks Jue..
     
    Nithy, Nov 13, 2007
    #7
  8. Nithy

    Nithy Guest

    Thanks for your prompt response Smallpond.
     
    Nithy, Nov 13, 2007
    #8
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.