~ubuntu-branches/ubuntu/hardy/ruby1.8/hardy-updates

« back to all changes in this revision

Viewing changes to ext/bigdecimal/sample/linear.rb

  • Committer: Bazaar Package Importer
  • Author(s): akira yamada
  • Date: 2007-03-13 22:11:58 UTC
  • mfrom: (1.1.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20070313221158-h3oql37brlaf2go2
Tags: 1.8.6-1
* new upstream version, 1.8.6.
* libruby1.8 conflicts with libopenssl-ruby1.8 (< 1.8.6) (closes: #410018)
* changed packaging style to cdbs from dbs.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/local/bin/ruby
 
2
 
 
3
#
 
4
# linear.rb
 
5
#
 
6
# Solves linear equation system(A*x = b) by LU decomposition method.
 
7
#  where  A is a coefficient matrix,x is an answer vector,b is a constant vector.
 
8
#
 
9
# USAGE:
 
10
#   ruby linear.rb [input file solved]
 
11
#
 
12
 
 
13
require "bigdecimal"
 
14
require "bigdecimal/ludcmp"
 
15
 
 
16
#
 
17
# NOTE:
 
18
#   Change following BigDecimal::limit() if needed.
 
19
BigDecimal::limit(100)
 
20
#
 
21
 
 
22
include LUSolve
 
23
def rd_order(na)
 
24
   printf("Number of equations ?") if(na <= 0)
 
25
   n = ARGF.gets().to_i
 
26
end
 
27
 
 
28
na   = ARGV.size
 
29
zero = BigDecimal::new("0.0")
 
30
one  = BigDecimal::new("1.0")
 
31
 
 
32
while (n=rd_order(na))>0
 
33
  a = []
 
34
  as= []
 
35
  b = []
 
36
  if na <= 0
 
37
     # Read data from console.
 
38
     printf("\nEnter coefficient matrix element A[i,j]\n");
 
39
     for i in 0...n do
 
40
       for j in 0...n do
 
41
         printf("A[%d,%d]? ",i,j); s = ARGF.gets
 
42
         a  << BigDecimal::new(s);
 
43
         as << BigDecimal::new(s);
 
44
       end
 
45
       printf("Contatant vector element b[%d] ? ",i); b << BigDecimal::new(ARGF.gets);
 
46
     end
 
47
  else
 
48
     # Read data from specified file.
 
49
     printf("Coefficient matrix and constant vector.\n");
 
50
     for i in 0...n do
 
51
       s = ARGF.gets
 
52
       printf("%d) %s",i,s)
 
53
       s = s.split
 
54
       for j in 0...n do
 
55
         a  << BigDecimal::new(s[j]);
 
56
         as << BigDecimal::new(s[j]);
 
57
       end
 
58
       b << BigDecimal::new(s[n]);
 
59
     end
 
60
  end
 
61
  x = lusolve(a,b,ludecomp(a,n,zero,one),zero)
 
62
  printf("Answer(x[i] & (A*x-b)[i]) follows\n")
 
63
  for i in 0...n do
 
64
     printf("x[%d]=%s ",i,x[i].to_s)
 
65
     s = zero
 
66
     for j in 0...n do
 
67
       s = s + as[i*n+j]*x[j]
 
68
     end
 
69
     printf(" & %s\n",(s-b[i]).to_s)
 
70
  end
 
71
end