Method: Stick::Matrix#determinant_e

Defined in:
lib/stick/matrix/core.rb

#determinant_eObject Also known as: det_e

Returns the determinant of the matrix. If the matrix is not square, the result is 0. This method’s algorism is Gaussian elimination method. This method uses Euclidean algorism. If all elements are integer, really exact value. But, if an element is a float, can’t return exact value.

Matrix[[7,6], [3,9]].determinant
  => 63


738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'lib/stick/matrix/core.rb', line 738

def determinant_e
  return 0 unless square?

  size = row_size - 1
  a = to_a

  det = 1
  k = 0
  begin
    if a[k][k].zero?
      i = k
      begin
        return 0 if (i += 1) > size
      end while a[i][k].zero?
      a[i], a[k] = a[k], a[i]
      det *= -1
    end
    (k + 1).upto(size) do |i|
      q = a[i][k].quo(a[k][k])
      k.upto(size) do |j|
        a[i][j] -= a[k][j] * q
      end
      unless a[i][k].zero?
        a[i], a[k] = a[k], a[i]
        det *= -1
        redo
      end
    end
    det *= a[k][k]
  end while (k += 1) <= size
  det
end