swapnil90
swapnil90

Reputation: 115

illegal division by zero:Perl

I have written a code to find determinant of a 10X10 matrix. This code gives the proper result till 9X9 matrix. But for 10X10 matrix gives the following error

"Use of Uninitialized value in multiplication <*> at line 23

Illegal division by zero at line 21"

I tried for 11X11 matrix also, but it is giving the wrong answer.

Why this code is giving such error...

Following is the code:

#!/usr/bin/perl
use strict; 
use warnings;

my @x1=(
  [5, 6, 3, 2, 4, 9, 3, 5, 4, 2], 
  [12, 9, 8, 3, 3, 0, 6, 9, 3, 4],
  [8, 6, 5, 8, 9, 3, 9, 3, 9, 5],
  [6, 4, 3, 0, 6, 4, 8, 2, 22, 8],
  [8, 3, 2, 5, 2, 12, 7, 1, 6, 9],
  [5, 9, 3, 9, 5, 1, 3, 8, 4, 2],
  [3, 10, 4, 16, 4, 7, 2, 12, 9, 6],
  [2, 12, 9, 13, 8, 3, 1, 16, 0, 6],
  [3, 6, 8, 5, 12, 8, 4, 19, 8, 5],
  [2, 5, 6, 4, 9, 10, 3, 11, 7, 3]
);
# Matrix of nxn
for (my $i=0;$i le 9;$i++) {
  for (my $j=0;$j le 9;$j++) {

      if($j>$i) {
         my $ratio = $x1[$j][$i]/$x1[$i][$i];
          for(my $k = 0; $k le 9; $k++){

              $x1[$j][$k] -= $ratio * $x1[$i][$k];
          }
      } 

  }
}

my $det1 = 1; 
for(my $i = 0; $i le 9; $i++){
  $det1 *= $x1[$i][$i];
}
printf $det1," ";

Upvotes: 3

Views: 612

Answers (1)

Sobrique
Sobrique

Reputation: 53508

le doesn't do what you think it does. http://perldoc.perl.org/perlop.html

Binary "le" returns true if the left argument is stringwise less than or equal to the right argument.

print 10 le 9,"\n";
print 10 <= 9,"\n";

It's a stringwise comparison not a numeric one.

So "10" le "9" is true, because alphabetically 10 is before 9.

But this would work fine for a smaller matrix, because 9 le 8 is a valid comparison and works the 'right way'.

You should use <= instead:

Binary "<=" returns true if the left argument is numerically less than or equal to the right argument.

You can also probably auto-scale by using $#x1 for your comparison, which is the value of the last array index. In your example above, $#x1 is 9, because your array is 0-9

Upvotes: 6

Related Questions