2003-03-28 00:00:21 -05:00
|
|
|
#!/usr/local/bin/ruby
|
|
|
|
|
|
|
|
#
|
|
|
|
# linear.rb
|
|
|
|
#
|
|
|
|
# Solves linear equation system(A*x = b) by LU decomposition method.
|
|
|
|
# where A is a coefficient matrix,x is an answer vector,b is a constant vector.
|
|
|
|
#
|
2003-10-20 23:18:44 -04:00
|
|
|
# USAGE:
|
|
|
|
# ruby linear.rb [input file solved]
|
|
|
|
#
|
|
|
|
|
2003-03-28 00:00:21 -05:00
|
|
|
require "bigdecimal"
|
2005-02-18 12:31:14 -05:00
|
|
|
require "bigdecimal/ludcmp"
|
2003-03-28 00:00:21 -05:00
|
|
|
|
2003-10-20 23:18:44 -04:00
|
|
|
#
|
|
|
|
# NOTE:
|
|
|
|
# Change following BigDecimal::limit() if needed.
|
|
|
|
BigDecimal::limit(100)
|
|
|
|
#
|
2003-03-28 00:00:21 -05:00
|
|
|
|
2003-10-20 23:18:44 -04:00
|
|
|
include LUSolve
|
|
|
|
def rd_order(na)
|
|
|
|
printf("Number of equations ?") if(na <= 0)
|
|
|
|
n = ARGF.gets().to_i
|
2003-03-28 00:00:21 -05:00
|
|
|
end
|
|
|
|
|
2003-10-20 23:18:44 -04:00
|
|
|
na = ARGV.size
|
2003-03-28 00:00:21 -05:00
|
|
|
zero = BigDecimal::new("0.0")
|
|
|
|
one = BigDecimal::new("1.0")
|
|
|
|
|
2003-10-20 23:18:44 -04:00
|
|
|
while (n=rd_order(na))>0
|
2003-03-28 00:00:21 -05:00
|
|
|
a = []
|
|
|
|
as= []
|
|
|
|
b = []
|
2003-10-20 23:18:44 -04:00
|
|
|
if na <= 0
|
|
|
|
# Read data from console.
|
|
|
|
printf("\nEnter coefficient matrix element A[i,j]\n");
|
|
|
|
for i in 0...n do
|
|
|
|
for j in 0...n do
|
|
|
|
printf("A[%d,%d]? ",i,j); s = ARGF.gets
|
|
|
|
a << BigDecimal::new(s);
|
|
|
|
as << BigDecimal::new(s);
|
|
|
|
end
|
|
|
|
printf("Contatant vector element b[%d] ? ",i); b << BigDecimal::new(ARGF.gets);
|
|
|
|
end
|
|
|
|
else
|
|
|
|
# Read data from specified file.
|
|
|
|
printf("Coefficient matrix and constant vector.\n");
|
|
|
|
for i in 0...n do
|
|
|
|
s = ARGF.gets
|
|
|
|
printf("%d) %s",i,s)
|
|
|
|
s = s.split
|
|
|
|
for j in 0...n do
|
|
|
|
a << BigDecimal::new(s[j]);
|
|
|
|
as << BigDecimal::new(s[j]);
|
|
|
|
end
|
|
|
|
b << BigDecimal::new(s[n]);
|
|
|
|
end
|
2003-03-28 00:00:21 -05:00
|
|
|
end
|
|
|
|
x = lusolve(a,b,ludecomp(a,n,zero,one),zero)
|
2003-10-20 23:18:44 -04:00
|
|
|
printf("Answer(x[i] & (A*x-b)[i]) follows\n")
|
2003-03-28 00:00:21 -05:00
|
|
|
for i in 0...n do
|
2003-10-20 23:18:44 -04:00
|
|
|
printf("x[%d]=%s ",i,x[i].to_s)
|
|
|
|
s = zero
|
|
|
|
for j in 0...n do
|
2003-03-28 00:00:21 -05:00
|
|
|
s = s + as[i*n+j]*x[j]
|
2003-10-20 23:18:44 -04:00
|
|
|
end
|
|
|
|
printf(" & %s\n",(s-b[i]).to_s)
|
2003-03-28 00:00:21 -05:00
|
|
|
end
|
|
|
|
end
|