-
#!/usr/bin/env lua
-
-
require 'determinant'
-
-
function Cramer(n)
-
assert(n>0)
-
-
local cramer={}
-
-
-- the coefficient determinant
-
cramer.D={}
-
-
-- this D1,D2,D3...
-
cramer.Ds={}
-
for i=1,n do
-
table.insert(cramer.Ds,{})
-
end
-
-
-- this number of unknown numbers
-
cramer.n=n
-
-
-- add an equation
-
-- for example:
-
-- x1+2x2-x3+3x4=2
-
-- use cramer:add(1,2,-1,3,2)
-
cramer.add=function(this,...)
-
local toadd={...}
-
assert(table.maxn(toadd)==this.n+1)
-
-
for i=1,this.n do
-
table.insert(this.D,toadd[i])
-
for j=1,this.n do
-
table.insert(this.Ds[j],toadd[i])
-
end
-
end
-
-
local last=toadd[this.n+1];
-
local times=table.maxn(this.D)/this.n
-
for i=1,this.n do
-
this.Ds[i][(times-1)*this.n+i]=last
-
end
-
end
-
-
-- Use Cramer Rules to solve linear equations
-
-- When solution does not exist, nil is returned,
-
-- and solution table returned otherwise.
-
cramer.solve=function(this)
-
assert(table.maxn(this.D)==this.n*this.n)
-
-
local D=Determinant(this.D):eval();
-
if D==0 then
-
return nil
-
end
-
-
local solutions={}
-
local Dn;
-
for i=1,this.n do
-
Dn=Determinant(this.Ds[i]):eval();
-
table.insert(solutions,Dn/D)
-
end
-
-
return solutions;
-
end
-
-
return cramer
-
end