Trouble with Matrix::inverse

R

rbovet

I decided to use Ruby to write a simple program to help my daughter
with her math homework, which involves solving systems of linear
equations using matrices. It's been a long time since I learned all
this stuff, but I think I still remember the basics of it. But I keep
getting answers that don't make sense to me when I use the
Matrix::inverse function. Can somebody help me out?

Here's a simple program:
#!/usr/bin/env ruby
require 'matrix'
c=Matrix[[1,2],[2,1]]
d=c.inverse
p1=c*d
puts "c is " +c.to_s
puts "d is " +d.to_s
puts "product is "+p1.to_s


And here are the results:
c is Matrix[[1, 2], [2, 1]]
d is Matrix[[-1, 1], [0, -1]]
product is Matrix[[-1, -1], [-2, 1]]

The problem is that any matrix multiplied by its inverse is supposed
to yield the appropriate identity matrix. In this case, the product
is definitely NOT the identity matrix.

I get the same results under Ruby 1.6.7, 1.6.8, and 1.8.0.

I humbly request that somebody illuminate me as to the error(s) of my
ways.

Thanks!

Ray
 
T

ts

r> #!/usr/bin/env ruby
r> require 'matrix'

add this line

require 'mathn'

r> c=Matrix[[1,2],[2,1]]

svg% cat b.rb
#!/usr/bin/ruby
require 'matrix'
require 'mathn'

c=Matrix[[1,2],[2,1]]
d=c.inverse
p1=c*d
puts "c is " +c.to_s
puts "d is " +d.to_s
puts "product is "+p1.to_s
svg%

svg% b.rb
c is Matrix[[1, 2], [2, 1]]
d is Matrix[[-1/3, 2/3], [2/3, -1/3]]
product is Matrix[[1, 0], [0, 1]]
svg%
 
R

rbovet

Lyle Johnson said:
ts said:
add this line

require 'mathn'

<snip>

Thanks for the reminder, Guy. It was using integer math since the
elements of the matrix are integers.

Ray, as an alternative to Guy's suggestion, you could also do this:

c = Matrix[ [1.0, 2.0], [2.0, 1.0]]
d = c.inverse
p1 = c*d

and get the expected results (using floating point arithmetic instead).


Lyle and Guy,

Thank you both for your rapid responses! It's a delight to get such
fast and informative replies to a question. Putting the values into a
floating point format made clear to me what the problem was, but the
real gem was to find out about the mathn class, which is really cool!
It makes it much more "human-like" in its mathematical prowess.

Ray
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top