Search code examples
perlfloating-pointnumerical

What's the smallest non-zero, positive floating-point number in Perl?


I have a program in Perl that works with probabilities that can occasionally be very small. Because of rounding error, sometimes one of the probabilities comes out to be zero. I'd like to do a check for the following:

use constant TINY_FLOAT => 1e-200;
my $prob = calculate_prob();
if ( $prob == 0 ) {
    $prob = TINY_FLOAT;
}

This works fine, but I actually see Perl producing numbers that are smaller than 1e-200 (I just saw a 8.14e-314 fly by). For my application I can change calculate_prob() so that it returns the maximum of TINY_FLOAT and the actual probability, but this made me curious about how floating point numbers are handled in Perl.

What's the smallest positive floating-point value in Perl? Is it platform-dependent? If so, is there a quick program that I can use to figure it out on my machine?


Solution

  • The other answers are good. Here is how to find out the approximate ε if you did not know any of that information and could not post your question on SO ;-)

     #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use constant MAX_COUNT => 2000;
    
    my ($x, $c);
    
    for (my $y = 1; $y; $y /= 2) {
        $x = $y;
        # guard against too many iterations
        last if ++$c > MAX_COUNT;
    }
    
    printf "%d : %.20g\n", $c, $x;
    

    Output:

    C:\Temp> thj
    1075 : 4.9406564584124654e-324