Illegal division by zero: Perl

I wrote some code to find the determinant of a 10X10 matrix. This code gives the correct result up to a 9X9 matrix. But for 10X10 matrix the following error appears

"Using uninitialized value when multiplying <*> on line 23

Illegal division by zero on line 21 "

I've tried 11X11 matrix too, but it gives the wrong answer.

Why is this code giving such an error ...

Below 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," ";

      

+3


source to share


1 answer


le

does not do what you think. http://perldoc.perl.org/perlop.html

Binary "le" returns true if the left argument is a string, less than or equal to the correct argument.

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

      

This string comparison is not numeric.

So, it is "10" le "9"

true because in alphabetical order 10

before 9

.



But this will work fine for a smaller matrix because it 9 le 8

is a valid comparison and works "correctly".

Instead, you should use <=

:

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

You can also auto-scale using $#x1

for comparison, which is the value of the last index of the array. The example above $#x1

is there 9

because your array0-9

+6


source







All Articles