Cramer's rule

From Rosetta Code
Revision as of 03:18, 28 January 2016 by Trizen (talk | contribs) (Create "Cramer's rule" draft task)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Cramer's rule is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

In linear algebra, Cramer's rule is an explicit formula for the solution of a system of linear equations with as many equations as unknowns, valid whenever the system has a unique solution. It expresses the solution in terms of the determinants of the (square) coefficient matrix and of matrices obtained from it by replacing one column by the vector of right hand sides of the equations.

Task

Given the following system of equations:

solve for , and , using Cramer's rule.

Perl 6

<lang perl6>sub det(@A) {

   [+] gather for ^@A -> $i {
       my ($p1, $p2) = (1, 1);
       for ^@A[$i] -> $j {
           $p1 *= @A[($j+$i)%@A][$j];
           $p2 *= @A[($j+$i)%@A][*-$j-1];
       }
       take $p1-$p2;
   }

}

sub cramers_rule(@A, @terms) {

   gather for ^@A -> $i {
       my @Ai = @A.map: { [|$_] };
       for ^@terms -> $j {
           @Ai[$j][$i] = @terms[$j];
       }
       take det(@Ai);
   } »/» det(@A);

}

my @matrix = (

   [2, -3,  1],
   [1, -2, -2],
   [3, -4,  1],

);

my @free_terms = (4, -6, 5); my ($x, $y, $z) = |cramers_rule(@matrix, @free_terms);

say "x = $x"; say "y = $y"; say "z = $z";</lang>

Output:
x = 2
y = 1
z = 3

Sidef

<lang ruby>func det(A) {

   var dt = 0
   var rows = A.len
   A.each_index { |i|
       var (p1=1, p2=1)
       A[i].each_index { |j|
           p1 *= A[(j+i)%rows][j]
           p2 *= A[(j+i)%rows][-j]
       }
       dt += p1-p2
   }
   dt

}

func cramers_rule(A, terms) {

   var dxyz = []
   A.each_index { |i|
       var Ai = A.map{.map{_}}
       terms.each_index { |j|
           Ai[j][i] = terms[j]
       }
       dxyz[i] = det(Ai)
   }
   dxyz »/» det(A)

}

var matrix = [

   [2, -3,  1],
   [1, -2, -2],
   [3, -4,  1],

]

var free_terms = [4, -6, 5] var (x, y, z) = cramers_rule(matrix, free_terms)...;

say "x = #{x}" say "y = #{y}" say "z = #{z}"</lang>

Output:
x = 2
y = 1
z = 3