Cramer's rule: Difference between revisions

m
→‎version 2: added a better way to express the equations.
m (→‎version 2: shrunk a function.)
m (→‎version 2: added a better way to express the equations.)
Line 2,436:
values= '-3 -32 -47 49' /*values of each matrix row of numbers.*/
variables= substr('abcdefghijklmnopqrstuvwxyz', 27 - words(values) ) /*variable names.*/
call makeM ' 2 -1 5 1 3 2 2 -6 1 3 3 -1 5 -2 -3 3'
do y=1 for sz; $= /*display the matrix (linear equations)*/
do x=1 for sz; $= $ right(psign(@.x.y), w)'*'substr(variables, x, 1)
end /*y*/ /* [↑] right─justify matrix elements.*/
say pad= left('', length($) - 2); say $ ' = ' right( word(values, y), wewv)
end /*x*/ /* [↑] obtain value of the equation. */
say; say
Line 2,449:
end /*i*/
end /*j*/
say left('', 10)pad substr(variables,k,1) ' = ' right(det(makeL())/det(mat),we digits()+2)
end /*k*/
exit 0 /*stick a fork in it, we're all done. */
Line 2,455:
makeL: $=; do x=1 for sz; do y=1 for sz; $= $ !.x.y; end; end; return $ /*matrix─►list*/
mSize: arg _; do sz=0 for 1e3; if sz*sz==_ then return; end; say 'error,bad matrix';exit 9
psign: parse arg num; if left(num, 1)\=='-' & x>1 then return "+"num; return num
/*──────────────────────────────────────────────────────────────────────────────────────*/
det: procedure; parse arg a b c d 1 nums; call mSize words(nums); _= 0
if sz==2 then return a*d - b*c
do j=1 for sz
Line 2,469 ⟶ 2,470:
end /*j*/
aa= aa - (-1 ** odd) * @.i.1 * det($)
end; /*i*/; return aa
/*──────────────────────────────────────────────────────────────────────────────────────*/
makeM: procedure expose @. values mat sz w wewv; parse arg mat; call mSize words(mat)
#= 0; wewv= digits()0; + 2; w= 0
do j=1 for sz; wv= max(wv, length( word( values, j) ) )
do k=1 for sz; #= #+1; @.k.j= word(mat, #); w= max(w, length(@.k.j) )
end /*k*/
end; /*j*/; w= w + 1; return</lang>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
2*w -1*x +5*y +1*z = -3
3*w +2*x +2*y -6*z = -32
1*w +3*x +3*y -1*z = -47
5*w -2*x -3*y +3*z = 49
 
 
w = 2
x = -12
y = -4
z = 1
</pre>