commit 5bd5f93da54d44aff6d22072252a76947d01a996 Author: Lito Nicolai Date: Sun Feb 15 10:44:53 2015 -0800 Matrix#inverse returns matrix of integers whenever possible diff --git a/ChangeLog b/ChangeLog index 8e7a96b..61dc486 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +Mon Feb 16 03:37:45 2015 Lito Nicolai + + * lib/matrix.rb (inverse_from): return a matrix of integers + whenever possible + + * test/matrix/test_matrix.rb (test_inverse): test for fix + Sat Feb 7 22:13:08 2015 Masaki Suketa * test/win32ole/test_win32ole_record.rb: remove test using .NET diff --git a/lib/matrix.rb b/lib/matrix.rb index fb98d09..e79c361 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1103,10 +1103,24 @@ class Matrix @rows[k][j] = @rows[k][j].quo(akk) end end - self + integral_from_rational(self) end private :inverse_from + def integral_from_rational(src) # :nodoc: + n = Matrix.build(src.row_count) do |i , j| + elem = src[i, j] + if elem.is_a?(Rational) && elem.denominator == 1 + elem.to_i + else + break + end + end + + n.nil? ? src : n + end + private :integral_from_rational + # # Matrix exponentiation. # Equivalent to multiplying the matrix by itself N times. diff --git a/test/matrix/test_matrix.rb b/test/matrix/test_matrix.rb index 3fdef3b..d8b95ec 100644 --- a/test/matrix/test_matrix.rb +++ b/test/matrix/test_matrix.rb @@ -174,8 +174,15 @@ class TestMatrix < Test::Unit::TestCase def test_inverse assert_equal(Matrix.empty(0, 0), Matrix.empty.inverse) - assert_equal(Matrix[[-1, 1], [0, -1]], Matrix[[-1, -1], [0, -1]].inverse) + assert Matrix[[-1, 1], [0, -1]].eql? Matrix[[-1, -1], [0, -1]].inverse + assert Matrix[[1, 2], [3, 4]].inverse.eql?( + Matrix[[Rational(-2), Rational(1)], + [Rational(3, 2), Rational(-1, 2)]] + ) assert_raise(ExceptionForMatrix::ErrDimensionMismatch) { @m1.inverse } + assert_raise(ExceptionForMatrix::ErrNotRegular) { + Matrix[[0, 0], [0, 0]].inverse + } end def test_determinant