How to check numerical overflow and overflow conditions in Perl?

I am doing a multiplication operation between two floating point variables. After that I need to check the numerical overflow, overflow and division by zero errors, if any.

How can i do this?

+3
source share
2 answers

Here you can check the overflow (in fact, it's just a floating point + infinity and -Infinity):

#!perl -w
use strict;

my $x = 10 ** 200;
my $positive_overflow = $x * $x;
my $negative_overflow = -$x * $x;

print is_infinity($positive_overflow) ? 'true' : 'false';
print "\n";
print is_infinity($negative_overflow) ? 'true' : 'false';
print "\n";

sub is_infinity
{
    my $x = shift;
    return $x =~ /inf/i;
}

Division by zero is difficult because you cannot perform division in a normal program area without it dying on you. You can wrap it in eval, though:

#!perl -w
use strict;

my $x = 100;
my $y = 0;

my $q = try_divide($x, $y);
print "Might be division by zero...\n" if !defined $q;

$y = 10;
$q = try_divide($x, $y);
print "$q\n";

sub try_divide
{
    my $x = shift;
    my $y = shift;
    my $q;

    eval { $q = $x / $y };

    return $q;
}
+3
source

, () , . , , , 1, - , ; , , , .

my $underflow_checker;
for ( my $i = 1; 1 + $i > 1; $i /= 2 ) { $underflow_checker = 1 + $i }
...
$x = 2**-520;
$y = 2**520;
$result = $x / $y;
if ( $result == 0 && $x != 0 || $result != 0 && $result * $underflow_checker == $result ) { print "Underflow!\n" }
+1

Source: https://habr.com/ru/post/1717119/


All Articles