解决gem NMatrix的功能

时间:2017-09-26 15:42:19

标签: ruby nmatrix

当我尝试在gem NMatrix中使用“解决”功能时,我发现错误的结果......

我正在尝试解决线性系统a*x = b其中

a = [[1,  0, 0], 
     [4, -5, 1],
     [0,  0, 1]]

b = [0, 0, 729]

哪个应该给出答案

x = [0, 145.8, 729]

我调用求解函数a.solve(b)(如http://www.rubydoc.info/gems/nmatrix/0.2.1/NMatrix#solve-instance_method所述),但它返回

x = [0, 1.013500790889141e-30, 1.013500790889141e-30]

因此,我有两个问题:

  1. 我做错了吗?
  2. 如果没有,用ruby解决矩阵系统的其他解决方案(不包括GSL)会是什么?
  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

要回答问题的第2部分,您可以使用Ruby的内置Matrix类。

require 'matrix'

m = Matrix[[1, 0, 0], [4, -5, 1], [0, 0, 1]]
  #=> Matrix[[1, 0, 0], [4, -5, 1], [0, 0, 1]]
b = Vector[0, 0, 729]
  #=> Vector[0, 0, 729]

a = m.lup.solve(b).to_a
  #=> [(0/1), (729/5), (729/1)]

如果有人喜欢浮动(而不是有理数),

a.map(&:to_f)
  #=> [0.0, 145.8, 729.0]

请参阅Matrix#lupMatrix::LUPDecomposition#solve,它们使用LU分解来解决线性系统。

如果线性方程组没有解(例如[[0,0], [0,0]]*x = b)或无限多个解(即m是单数),Ruby将引发异常。例如,

Matrix[[0,0],[0,0]].lup.solve [1, 1]
  #=> ExceptionForMatrix::ErrNotRegular: Not Regular Matrix

require matrix使MatrixVector类(和子类)可供使用。