Cramer's rule: Difference between revisions
Added Easylang
Thundergnat (talk | contribs) m (→{{header|C sharp}}: Regularize header markup to recommended on category page) |
(Added Easylang) |
||
(7 intermediate revisions by 7 users not shown) | |||
Line 40:
{{trans|Nim}}
<
V m = copy(mm)
V result = 1.0
Line 82:
L(i) 0 .< A.len
print(‘#3.3’.format(cramerSolve(A, detA, B, i)))</
{{out}}
Line 93:
=={{header|Ada}}==
<
with Ada.Numerics.Generic_Real_Arrays;
Line 162:
begin
Put (R);
end Cramers_Rules;</
{{out}}
Line 170:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the non-standard DET operator available in Algol 68G.
<
# this is for REAL arrays, could define additional operators #
# for INT, COMPL, etc. #
Line 217:
OD;
print( ( newline ) )
</syntaxhighlight>
{{out}}
<pre>
Line 225:
=={{header|C}}==
<
#include <stdio.h>
#include <stdlib.h>
Line 336:
deinit_square_matrix(A);
return EXIT_SUCCESS;
}</
{{out}}
Line 346:
=={{header|C sharp|C#}}==
Instead of copying a bunch of arrays, I made a class with an indexer that simply accesses the correct items in the original matrix.
<
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 447:
}
}</
{{out}}
<pre>
Line 455:
=={{header|C++}}==
{{trans|C#}}
<
#include <iostream>
#include <vector>
Line 591:
return 0;
}</
{{out}}
<pre>[2, -12, -4, 1]</pre>
=={{header|Common Lisp}}==
<
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
Line 636:
(1 3 3 -1)
(5 -2 -3 3))
#(-3 -32 -47 49))</
{{out}}
<pre>(2 -12 -4 1)</pre>
Line 642:
=={{header|D}}==
{{trans|Kotlin}}
<
import std.range : iota;
import std.stdio : writeln;
Line 727:
auto wxyz = cramer(m, d);
writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]);
}</
{{out}}
<pre>w = 2, x = -12, y = -4, z = 1</pre>
=={{header|EasyLang}}==
{{trans|Phix}}
<syntaxhighlight>
proc det . a0[][] res .
res = 1
a[][] = a0[][]
n = len a[][]
for j to n
imax = j
for i = j + 1 to n
if a[i][j] > a[imax][j]
imax = i
.
.
if imax <> j
swap a[imax][] a[j][]
res = -res
.
if abs a[j][j] < 1e-12
print "Singular matrix!"
res = 0 / 0
return
.
for i = j + 1 to n
mult = -a[i][j] / a[j][j]
for k to n
a[i][k] += mult * a[j][k]
.
.
.
for i to n
res *= a[i][i]
.
.
proc cramer_solve . a0[][] deta b[] col res .
a[][] = a0[][]
for i to len a[][]
a[i][col] = b[i]
.
det a[][] d
res = d / deta
.
a[][] = [ [ 2 -1 5 1 ] [ 3 2 2 -6 ] [ 1 3 3 -1 ] [ 5 -2 -3 3 ] ]
b[] = [ -3 -32 -47 49 ]
det a[][] deta
for i to len a[][]
cramer_solve a[][] deta b[] i r
print r
.
</syntaxhighlight>
{{out}}
<pre>
2.00
-12
-4
1.00
</pre>
=={{header|EchoLisp}}==
<
(lib 'matrix)
(string-delimiter "")
Line 749 ⟶ 807:
(writeln "B = " B)
(writeln "X = " (cramer A B)))
</syntaxhighlight>
{{out}}
<pre>
Line 763 ⟶ 821:
=={{header|Factor}}==
<
IN: rosetta-code.cramers-rule
Line 782 ⟶ 840:
{ -3 -32 -47 49 } solve . ;
MAIN: cramers-rule-demo</
{{out}}
<pre>
Line 798 ⟶ 856:
With matrices, there is a problem all the way from the start in 1958. Everyone agrees that a matrix should be indexed as A(''row'',''column'') and that when written out, rows should run down the page and columns across. This is unexceptional and the F90 function MATMUL follows this usage. However, Fortran has always stored its array elements in what is called "column major" order, which is to say that element A(1,1) is followed by element A(2,1) in storage, not A(1,2). Thus, if an array is written (or read) by something like <code>WRITE (6,*) A</code>, consecutive elements, written along a line, will be A(1,1), A(2,1), A(3,1), ... So, subroutine SHOWMATRIX is employed to write the matrix out in the desired form, and to read the values into the array, an explicit loop is used to place them where expected rather than just <code>READ(INF,*) A</code>
Similarly, if instead a DATA statement were used to initialise the array for the example problem, and it looked something like <
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/</
I have never seen an explanation of why this choice was made for Fortran.<
INTEGER MSG !Might as well be here.
CONTAINS !The details.
Line 910 ⟶ 968:
Closedown.
100 WRITE (6,*) "That was interesting." !Quite.
END !Open files are closed, allocated memory is released. </
Oddly, the Compaq Visual Fortran F90/95 compiler is confused by the usage "BAD IDEA" instead of "BADIDEA" - spaces are not normally relevant in Fortran source. Anyway, file Test.dat has been filled with the numbers of the example, as follows:
Line 940 ⟶ 998:
=={{header|FreeBASIC}}==
<
Function determinant(matrix() As Double) As Double
Dim As long n=Ubound(matrix,1),sign=1
Line 1,019 ⟶ 1,077:
Next
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 1,030 ⟶ 1,088:
=={{header|Go}}==
'''Library gonum:'''
<
import (
Line 1,058 ⟶ 1,116:
}
fmt.Println(x)
}</
{{out}}
<pre>
Line 1,064 ⟶ 1,122:
</pre>
'''Library go.matrix:'''
<
import (
Line 1,092 ⟶ 1,150:
}
fmt.Println(x)
}</
{{out}}
<pre>
Line 1,100 ⟶ 1,158:
=={{header|Groovy}}==
{{trans|Java}}
<
static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),
Line 1,193 ⟶ 1,251:
}
}
}</
{{out}}
<pre>Solution = [2.0, -12.0, -4.0, 1.0]</pre>
Line 1,199 ⟶ 1,257:
=={{header|Haskell}}==
===Version 1===
<
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
Line 1,215 ⟶ 1,273:
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-3], [-32], [-47], [49]]</
{{out}}
Line 1,223 ⟶ 1,281:
We use Rational numbers for having more precision.
a % b is the rational a / b.
<
s_permutations = flip zip (cycle [1, -1]) . (foldl aux [[]])
where aux items x = do
Line 1,302 ⟶ 1,360:
let b = [[-3], [-32], [-47], [49]]
task a b
</syntaxhighlight>
{{out}}
<pre>
Line 1,359 ⟶ 1,417:
===Version 3===
<
determinant::(Fractional a, Ord a) => [[a]] -> a
Line 1,431 ⟶ 1,489:
let b = [[-3], [-32], [-47], [49]]
task a b
</syntaxhighlight>
{{out}}
<pre>
Line 1,490 ⟶ 1,548:
Implementation:
<
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
)</
Task data:
<
2 -1 5 1
3 2 2 -6
Line 1,505 ⟶ 1,563:
)
b=: _3 _32 _47 49</
Task example:
<
2 _12 _4 1</
=={{header|Java}}==
Supports double data type. A more robust solution would support arbitrary precision integers, arbitrary precision decimals, arbitrary precision rationals, or even arbitrary precision algebraic numbers.
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.Arrays;
Line 1,618 ⟶ 1,676:
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,626 ⟶ 1,684:
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
var matrix = [
[2, -1, 5, 1],
Line 1,718 ⟶ 1,776:
}
</syntaxhighlight>
{{out}}
<pre>[ 2, -12, -4, 1 ]</pre>
Line 1,729 ⟶ 1,787:
(*) Note that cramer(a;d) as defined here assumes that d is a 1-d vector
in accordance with the task description and common practice.
<
# Assumptions: the input is square and the indices are hunky dory.
def minor(rowNum; colNum):
Line 1,767 ⟶ 1,825:
| (a | det) as $ad
| if $ad == 0 then "matrix determinant is 0" | error
(reduce range(0; $n) as $r (a; .[$r][$c] = d[$r])) as $aa
| .[$c] = ($aa|det) / $ad )
end ;
def a: [
Line 1,781 ⟶ 1,840:
[ -3, -32, -47, 49 ] ;
"Solution is \(cramer(a; d))"</
{{out}}
<pre>
Solution is [2,-12,-4,1]
</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
Line 1,799 ⟶ 1,859:
b = [-3, -32, -47, 49]
@show cramersolve(A, b)</
{{out}}
Line 1,806 ⟶ 1,866:
Note that it is entirely impractical to use Cramer's rule in this situation. It would be much better to use the built-in operator for solving linear systems. Assuming that the coefficient matrix and constant vector are defined as before, the solution vector is given by:
<syntaxhighlight lang
=={{header|Kotlin}}==
As in the case of the [[Matrix arithmetic]] task, I've used the Johnson-Trotter permutations generator to assist with the calculation of the determinants for the various matrices:
<
typealias Vector = DoubleArray
Line 1,878 ⟶ 1,938:
val (w, x, y, z) = cramer(m, d)
println("w = $w, x = $x, y = $y, z = $z")
}</
{{out}}
Line 1,886 ⟶ 1,946:
=={{header|Lua}}==
<
local function cramer(mat, vec)
Line 1,927 ⟶ 1,987:
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
</syntaxhighlight>
{{out}}
Line 1,933 ⟶ 1,993:
=={{header|Maple}}==
<
cramer:=proc(A,B)
local n,d,X,V,i;
Line 1,950 ⟶ 2,010:
A:=Matrix([[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]):
B:=Vector([-3,-32,-47,49]):
printf("%a",cramer(A,B));</
{{out}}
Line 1,957 ⟶ 2,017:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
Line 1,965 ⟶ 2,025:
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-3, -32, -47, 49}]</
{{out}}
Line 1,971 ⟶ 2,031:
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
(%i1) eqns: [ 2*w-x+5*y+z=-3, 3*w+2*x+2*y-6*z=-32, w+3*x+3*y-z=-47, 5*w-2*x-3*y+3*z=49];
(%o1) [z + 5 y - x + 2 w = - 3, (- 6 z) + 2 y + 2 x + 3 w = - 32,
Line 2,000 ⟶ 2,060:
(%i6) linsolve(eqns, [w,x,y,z]);
(%o6) [w = 2, x = - 12, y = - 4, z = 1]
</syntaxhighlight>
=={{header|Nim}}==
{{trans|Phix}}
<
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
Line 2,083 ⟶ 2,143:
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}"</
{{out}}
Line 2,093 ⟶ 2,153:
=={{header|PARI/GP}}==
<
M = [2,-1,5,1;3,2,2,-6;1,3,3,-1;5,-2,-3,3];
V = Col([-3,-32,-47,49]);
matadjoint(M) * V / matdet(M)
</syntaxhighlight>
Output:
Line 2,104 ⟶ 2,164:
=={{header|Perl}}==
<
sub cramers_rule {
Line 2,133 ⟶ 2,193:
print "x = $x\n";
print "y = $y\n";
print "z = $z\n";</
{{out}}
<pre>
Line 2,146 ⟶ 2,206:
<del>The copy-on-write semantics of Phix really shine here; because there is no explicit return/re-assign, you can treat parameters as a private workspace, confident in the knowledge that the updated version will be quietly discarded; all the copying and freeing of the C version is automatic/unnecessary here.</del><br>
UPDATE: For the next release, "with js" (or "with javascript_semantics") diables said copy-on-write semantics, so this now needs a couple of deep_copy() calls.
<!--<
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.4"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">with</span> <span style="color: #000000;">javascript_semantics</span>
Line 2,208 ⟶ 2,268:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"%7.3f\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cramer_solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">det_a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{Out}}
<pre>
Line 2,219 ⟶ 2,279:
=={{header|Prolog}}==
{{works with|GNU Prolog}}
<
removeElement([Head|Tail], J, [Head|X]) :-
J_2 is J - 1,
Line 2,282 ⟶ 2,342:
],
B = [-3, -32, -47, 49],
cramer(A, B, X).</
{{out}}
Line 2,292 ⟶ 2,352:
=={{header|Python}}==
<
def det(m,n):
if n==1: return m[0][0]
Line 2,306 ⟶ 2,366:
else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)]
print(r)
</syntaxhighlight>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(require math/matrix)
(define sys
(matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define soln
(define
(matrix-augment (list-set (matrix-cols M) idx new-col)))
(define
(let ([denom (matrix-determinant M)]
[nvars (matrix-num-cols
(letrec ([roots (λ (position)
(if (>= position nvars)
'()
(cons (/ (matrix-determinant
(matrix-set-column M soln position))
denom)
(roots (add1 position)))))])
(map cons '(w x y z) (roots 0)))))
(cramers-rule sys soln)
</syntaxhighlight>
{{out}}
<pre>'
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my @a = @matrix.map: { [|$_] };
my $sign =
my $pivot = 1;
for ^@a ->
my @r = (
my $previous-pivot = $pivot;
if 0 == ($pivot = @a[
(my
(@a[
my $pivot = @a[
$sign = -$sign;
}
for @r X @r -> (
((@a[
}
}
$sign
}
sub cramers_rule(@A, @terms) {
gather for ^@A ->
my @Ai = @A.map: { [|$_] };
for ^@terms ->
@Ai[
}
take det(@Ai);
Line 2,369 ⟶ 2,443:
);
my @free_terms =
my ($w, $x, $y, $z) =
("w = $w", "x = $x", "y = $y", "z = $z").join("\n").say;</syntaxhighlight>
{{out}}
<pre>
Line 2,386 ⟶ 2,456:
=={{header|REXX}}==
=== version 1 ===
<
Numeric Digits 20
names='w x y z'
Line 2,523 ⟶ 2,593:
dbg: Return</
{{out}}
<pre> 2 -1 5 1 -3
Line 2,551 ⟶ 2,621:
* eschewed the deprecated use of: ''call func(args)'' syntax
* automatically used the minimum width when showing the matrix elements and equation values
<
values= '-3 -32 -47 49' /*values of each matrix row of numbers.*/
variables= substr('abcdefghijklmnopqrstuvwxyz', 27 - words(values) ) /*variable names.*/
Line 2,595 ⟶ 2,665:
do k=1 for sz; #= #+1; @.k.j= word(mat, #); w= max(w, length(@.k.j))
end /*k*/
end; /*j*/; w= w + 1; return</
{{out|output|text= when using the internal default inputs:}}
<pre>
Line 2,610 ⟶ 2,680:
</pre>
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
===Explicit Cramer's rule===
≪ '''IF''' OVER DET
'''THEN'''
LAST ROT DUP SIZE 1 GET → vect det mtx dim
≪ 1 dim '''FOR''' c
mtx
1 dim '''FOR''' r
r c 2 →LIST vect r GET PUT
'''NEXT'''
DET det /
'''NEXT'''
dim →ARRY
≫
'''END'''
≫
‘CRAMR’ STO
[[ 2 -1 5 1 ][ 3 2 2 -6 ][ 1 3 3 -1 ][ 5 -2 -3 3 ]]
[ -3 -32 -47 49 ] CRAMR
{{out}}
<pre>
1: [ 2 -12 -4 1 ]
</pre>
===Implicit Cramer's rule===
RPL use Cramer's rule for its built-in equation system resolution feature, performed by the <code>/</code> instruction.
[ -3 -32 -47 49 ]
[[ 2 -1 5 1 ][ 3 2 2 -6 ][ 1 3 3 -1 ][ 5 -2 -3 3 ]]
/
{{out}}
<pre>
1: [ 2 -12 -4 1 ]
</pre>
=={{header|Ruby}}==
<
def cramers_rule(a, terms)
Line 2,631 ⟶ 2,736:
vector = [-3, -32, -47, 49]
puts cramers_rule(matrix, vector)</
{{out}}
<pre>
Line 2,641 ⟶ 2,746:
=={{header|Rust}}==
<
fn main() {
Line 2,728 ⟶ 2,833:
&mut self.elts[m * i..m * (i + 1)]
}
}</
Which outputs:
Line 2,734 ⟶ 2,839:
=={{header|Sidef}}==
<
gather {
for i in ^A {
Line 2,759 ⟶ 2,864:
say "x = #{x}"
say "y = #{y}"
say "z = #{z}"</
{{out}}
<pre>
Line 2,769 ⟶ 2,874:
=={{header|Tcl}}==
<
package require math::linearalgebra
namespace path ::math::linearalgebra
Line 2,790 ⟶ 2,895:
puts [format "%0.4f" $v] ;# format and display result
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,800 ⟶ 2,905:
=={{header|VBA}}==
<syntaxhighlight lang="vba">
Sub CramersRule()
OrigM = [{2, -1, 5, 1; 3,2,2,-6;1,3,3,-1;5,-2,-3,3}]
Line 2,820 ⟶ 2,925:
End Sub
</syntaxhighlight>
{{out}}
<pre>
Line 2,831 ⟶ 2,936:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Imports System.Linq.Enumerable
Line 2,935 ⟶ 3,040:
End Sub
End Module</
{{out}}
<pre>2, -12, -4, 1</pre>
Line 2,941 ⟶ 3,046:
=={{header|Wren}}==
{{libheader|Wren-matrix}}
<
var cramer = Fn.new { |a, d|
Line 2,970 ⟶ 3,075:
var x = cramer.call(a, d)
System.print("Solution is %(x)")</
{{out}}
<pre>
Solution is [2, -12, -4, 1]
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">
func Det(A, N); \Return value of determinate A, order N
int A, N;
int B, Sum, I, K, L, Term;
[if N = 1 then return A(0, 0);
B:= Reserve((N-1)*4\IntSize\);
Sum:= 0;
for I:= 0 to N-1 do
[L:= 0;
for K:= 0 to N-1 do
if K # I then
[B(L):= @A(K, 1); L:= L+1];
Term:= A(I, 0) * Det(B, N-1);
if I & 1 then Term:= -Term;
Sum:= Sum + Term;
];
return Sum;
];
real D;
[D:= float(Det([[2,-1,5,1], [3,2,2,-6], [1,3,3,-1], [5,-2,-3,3]], 4));
RlOut(0, float(Det([[-3,-1,5,1], [-32,2,2,-6], [-47,3,3,-1], [49,-2,-3,3]], 4)) / D);
RlOut(0, float(Det([[2,-3,5,1], [3,-32,2,-6], [1,-47,3,-1], [5,49,-3,3]], 4)) / D);
RlOut(0, float(Det([[2,-1,-3,1], [3,2,-32,-6], [1,3,-47,-1], [5,-2,49,3]], 4)) / D);
RlOut(0, float(Det([[2,-1,5,-3], [3,2,2,-32], [1,3,3,-47], [5,-2,-3,49]], 4)) / D);
]</syntaxhighlight>
{{out}}
<pre>
2.00000 -12.00000 -4.00000 1.00000
</pre>
=={{header|zkl}}==
Using the GNU Scientific Library, we define the values:
<
A:=GSL.Matrix(4,4).set(2,-1, 5, 1,
3, 2, 2,-6,
1, 3, 3,-1,
5,-2,-3, 3);
b:=GSL.Vector(4).set(-3,-32,-47,49);</
First, just let GSL solve:
<
Actually implement Cramer's rule:
{{Trans|Julia}}
<
b.len().pump(GSL.Vector(b.len()),'wrap(i){ // put calculations into new Vector
A.copy().setColumn(i,b).det();
}).close()/A.det();
}
cramersRule(A,b).format().println();</
{{out}}
<pre>
|