在Haskell中实现Gauss-Jordan消除 [英] Implement Gauss-Jordan elimination in Haskell

查看:108
本文介绍了在Haskell中实现Gauss-Jordan消除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想要编程高斯消元来计算一个基础(线性代数)作为我们自己的练习。这不是作业。



我首先想到了 [[Int]] 作为矩阵的结构。那时我就​​认为我们可以按照字典顺序排列列表。但是,我们必须用矩阵来计算。这就是问题所在。有人可以给我们一些提示。

解决方案

考虑使用 hmatrix 包。在它的模块中,您可以找到一个快速矩阵的实现和很多线性代数算法。浏览它们的源代码可能会帮助你解决疑惑。

下面是一个简单的例子,通过将矩阵分割成行来添加一行到另一行。

  import Numeric.Container 
import Data.Packed.Matrix

addRow :: Container Vector t => Int - > Int - >矩阵t - > Matrix t
addRow from to m = let rows = toRows m in
fromRows $ take to rows ++
[(rows !! from)`add`(rows !! to)] + +
drop(to + 1)rows

另一个例子,这次通过使用矩阵乘法。

  addRow ::(Product e,Container Vector e)=> 
Int - > Int - >矩阵e - > Matrix e
addRow from to m = m`add`(e 其中
nrows = rows m
e = buildMatrix nrows nrows
(\\ \\(r,c) - > if(r,c)/ =(to,from)then 0 else 1)



Cf。 容器 Vector 产品


We want to program the gauss-elimination to calculate a basis (linear algebra) as exercise for ourselves. It is not homework.

I thought first of [[Int]] as structure for our matrix. I thought then that we can sort the lists lexicographically. But then we must calculate with the matrix. And there is the problem. Can someone give us some hints.

解决方案

Consider using matrices from the hmatrix package. Among its modules you can find both a fast implementation of a matrix and a lot of linear algebra algorithms. Browsing their sources might help you with your doubts.

Here's a simple example of adding one row to another by splitting the matrix into rows.

import Numeric.Container
import Data.Packed.Matrix

addRow :: Container Vector t => Int -> Int -> Matrix t -> Matrix t
addRow from to m = let rows = toRows m in
  fromRows $ take to rows ++
             [(rows !! from) `add` (rows !! to)] ++
             drop (to + 1) rows

Another example, this time by using matrix multiplication.

addRow :: (Product e, Container Vector e) =>
          Int -> Int -> Matrix e -> Matrix e
addRow from to m = m `add` (e <> m)
  where
    nrows = rows m
    e = buildMatrix nrows nrows
        (\(r,c) -> if (r,c) /= (to,from) then 0 else 1)

Cf. Container, Vector, Product.

这篇关于在Haskell中实现Gauss-Jordan消除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆