LU decomposition: Difference between revisions
m
syntax highlighting fixup automation
SqrtNegInf (talk | contribs) m (→{{header|Raku}}: oops, fix variable name) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 194:
{{trans|Python}}
<
L(row) m
print(row)
Line 243:
L(part) lu(b)
pprint(part)
print()</
{{out}}
Line 279:
{{works with|Ada 2005}}
decomposition.ads:
<
generic
with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);
Line 287:
procedure Decompose (A : Matrix.Real_Matrix; P, L, U : out Matrix.Real_Matrix);
end Decomposition;</
decomposition.adb:
<
procedure Swap_Rows (M : in out Matrix.Real_Matrix; From, To : Natural) is
Line 366:
end Decompose;
end Decomposition;</
Example usage:
<
with Ada.Text_IO;
with Decomposition;
Line 421:
Ada.Text_IO.Put_Line ("U:"); Print (U_2);
Ada.Text_IO.Put_Line ("P:"); Print (P_2);
end Decompose_Example;</
{{out}}
Line 465:
=={{header|AutoHotkey}}==
<
LU_decomposition(A){
P := Pivot(A)
Line 536:
return "[" Trim(output, "`n,") "]"
}
;--------------------------</
Examples:<
, [2, 4, 7]
, [1, 1, 0]]
Line 556:
}
MsgBox, 262144, , % result
return</
{{out}}
<pre>A:=
Line 604:
=={{header|BBC BASIC}}==
<
A1() = 1, 3, 5, 2, 4, 7, 1, 1, 0
PROCLUdecomposition(A1(), L1(), U1(), P1())
Line 663:
a$ = LEFT$(LEFT$(a$)) + CHR$(13) + CHR$(10)
NEXT i%
= a$</
{{out}}
<pre>
Line 701:
=={{header|C}}==
Compiled with <code>gcc -std=gnu99 -Wall -lm -pedantic</code>. Demonstrating how to do LU decomposition, and how (not) to use macros. <
#include <stdlib.h>
#include <math.h>
Line 829:
return 0;
}</
=={{header|C++}}==
<
#include <cmath>
#include <iomanip>
Line 1,015:
return 0;
}</
{{out}}
Line 1,098:
Uses the routine (mmul A B) from [[Matrix multiplication]].
<
(defun eye (n)
(let ((I (make-array `(,n ,n) :initial-element 0)))
Line 1,156:
;; Return L, U and P.
(values L U P)))</
Example 1:
<
#2A((1 3 5) (2 4 7) (1 1 0))
Line 1,166:
#2A((1 0 0) (1/2 1 0) (1/2 -1 1))
#2A((2 4 7) (0 1 3/2) (0 0 -2))
#2A((0 1 0) (1 0 0) (0 0 1))</
Example 2:
<
#2A((11 9 24 2) (1 5 2 6) (3 17 18 1) (2 5 7 1))
Line 1,176:
#2A((1 0 0 0) (3/11 1 0 0) (1/11 23/80 1 0) (2/11 37/160 1/278 1))
#2A((11 9 24 2) (0 160/11 126/11 5/11) (0 0 -139/40 91/16) (0 0 0 71/139))
#2A((1 0 0 0) (0 0 1 0) (0 1 0 0) (0 0 0 1))</
=={{header|D}}==
{{trans|Common Lisp}}
<
std.array, std.conv, std.string, std.range;
Line 1,284:
foreach (immutable m; [a, b])
writefln(f, lu(m).tupleof);
}</
{{out}}
<pre>[[1.0, 0.0, 0.0],
Line 1,315:
=={{header|EchoLisp}}==
<
(lib 'matrix) ;; the matrix library provides LU-decomposition
(decimals 5)
Line 1,354:
0 0 -3.475 5.6875
0 0 0 0.51079
</syntaxhighlight>
=={{header|Fortran}}==
<
implicit none
call check( reshape([real(8)::1,2,1,3,4,1,5,7,0 ],[3,3]) )
Line 1,425:
end subroutine
end program</
{{out}}
<pre>
Line 1,473:
===2D representation===
{{trans|Common Lisp}}
<
import "fmt"
Line 1,582:
u.print("u")
p.print("p")
}</
{{out}}
<pre>
Line 1,624:
</pre>
===Flat representation===
<
import "fmt"
Line 1,746:
u.print("u")
p.print("p")
}</
Output is same as from 2D solution.
===Library gonum/mat===
<
import (
Line 1,782:
fmt.Printf("u: %.5f\n\n", mat.Formatted(u, mat.Prefix(" ")))
fmt.Println("p:", lu.Pivot(nil))
}</
{{out}}
Pivot format is a little different here. (But library solutions don't really meet task requirements anyway.)
Line 1,819:
===Library go.matrix===
<
import (
Line 1,845:
fmt.Printf("u:\n%v\n", u)
fmt.Printf("p:\n%v\n", p)
}</
{{out}}
<pre>
Line 1,889:
=={{header|Haskell}}==
''Without elem-at-index modifications; doesn't find maximum but any non-zero element''
<syntaxhighlight lang="haskell">
import Data.List
import Data.Maybe
Line 1,959:
main = putStrLn "Task1: \n" >> solveTask mY1 >>
putStrLn "Task2: \n" >> solveTask mY2
</syntaxhighlight>
{{out}}
<pre>
Line 2,024:
===With Numeric.LinearAlgebra===
<
a1, a2 :: Matrix R
Line 2,040:
main = do
print $ lu a1
print $ lu a2</
{{out}}
<pre>((3><3)
Line 2,072:
'''Solution:'''
<syntaxhighlight lang="idris">
module Main
Line 2,228:
putStrLn "Solution 2:"
printEx ex2
</syntaxhighlight>
{{out}}
Line 2,252:
'''Solution:'''
<
LU=: 3 : 0
Line 2,274:
permtomat=: 1 {.~"0 -@>:@:/:
LUdecompose=: (permtomat&.>@{. , }.)@:LU</
'''Example use:'''
<
LUdecompose A
┌─────┬─────┬───────┐
Line 2,301:
1 5 2 6
3 17 18 1
2 5 7 1</
=={{header|Java}}==
Translation of [[#Common_Lisp|Common Lisp]] via [[#D|D]]
{{works with|Java|8}}
<
import java.util.Locale;
import static java.util.stream.IntStream.range;
Line 2,402:
print(m);
}
}</
<pre> 1.0 0.0 0.0
0.5 1.0 0.0
Line 2,433:
=={{header|Javascript}}==
{{works with|ES5 ES6}}
<
const mult=(a, b)=>{
let res = new Array(a.length);
Line 2,512:
return [...lu(A),P];
}
</syntaxhighlight>
=={{header|jq}}==
Line 2,521:
'''Infrastructure'''
<
def matrix(m; n; init):
if m == 0 then []
Line 2,565:
| reduce range (0;$length) as $i
(""; . + reduce range(0;$length) as $j
(""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;</
'''LU decomposition'''
<
# Use "range(0;$n) as $i" to handle ill-conditioned cases.
def pivotize:
Line 2,609:
| . + [ $P ]
;
</syntaxhighlight>
'''Example 1''':
<
a | lup[] | neatly(4)
</syntaxhighlight>
{{Out}}
<
1 0 0
0.5 1 0
Line 2,627:
1 0 0
0 0 1
</syntaxhighlight>
'''Example 2''':
<
b | lup[] | neatly(21)</
{{Out}}
<
1 0 0 0
0.2727272727272727 1 0 0
Line 2,646:
0 0 1 0
0 1 0 0
0 0 0 1</
'''Example 3''':
<syntaxhighlight lang="jq">
# A|lup|verify(A) should be true
def verify(A):
Line 2,661:
[0, 0, 1, -1]];
A|lup|verify(A)</
{{out}}
true
Line 2,683:
=={{header|Kotlin}}==
<
typealias Vector = DoubleArray
Line 2,784:
printMatrix("U:", u2, "%8.5f")
printMatrix("P:", p2, "%1.0f")
}</
{{out}}
Line 2,846:
=={{header|Lobster}}==
<
// derived from JAMA v1.03
Line 2,950:
print_L A
print_U A
print_P piv</
{{out}}
<pre>
Line 2,992:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
A:=<<1.0|3.0|5.0>,<2.0|4.0|7.0>,<1.0|1.0|0.0>>:
LinearAlgebra:-LUDecomposition(A);
</syntaxhighlight>
{{out}}
<pre>
Line 3,005:
[0 0 1] [0.500000000000000 -1. 1.0] [0. 0. -2.]
</pre>
<syntaxhighlight lang="maple">
A:=<<11.0|9.0|24.0|2.0>,<1.0|5.0|2.0|6.0>,
<3.0|17.0|18.0|1.0>,<2.0|5.0|7.0|1.0>>:
Line 3,012:
LUDecomposition(A);
</syntaxhighlight>
{{out}}
<pre>
Line 3,042:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{lu, p, c} = LUDecomposition[a];
l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[p]];
Line 3,055:
P = Part[IdentityMatrix[Length[p]], p] ;
MatrixForm /@ {P.a , P, l, u, l.u}
</syntaxhighlight>
{{out}}
[[File:LUex1.png]]
Line 3,064:
LU decomposition is part of language
<
1 3 5
2 4 7
1 1 0];
[L,U,P] = lu(A)</
{{out}}
<pre>
Line 3,091:
</pre>
2nd example:
<
11 9 24 2
1 5 2 6
Line 3,097:
2 5 7 1 ];
[L,U,P] = lu(A)</
{{out}}
<pre>
Line 3,123:
===Creating a MATLAB function===
<syntaxhighlight lang="matlab">
function [ P, L, U ] = LUdecomposition(A)
Line 3,181:
end
</syntaxhighlight>
=={{header|Maxima}}==
<
a: hilbert_matrix(4)$
Line 3,220:
lu_backsub(lup, transpose([1, 1, -1, -1]));
/* matrix([-204], [2100], [-4740], [2940]) */</
=={{header|Nim}}==
Line 3,228:
For display, we use the third party module "strfmt" which allows to specify dynamically the format.
<
import strfmt
Line 3,314:
l2.print("L:", "8.5f")
u2.print("U:", "8.5f")
p2.print("P:", "1.0f")</
{{out}}
Line 3,367:
=={{header|PARI/GP}}==
<
{
my (L = matid(#M), U = M, P = L);
Line 3,389:
[L,U,P] \\ return L,U,P triple matrix
}</
Output:
Line 3,454:
=={{header|Perl}}==
{{trans|Raku}}
<
for $test (
Line 3,538:
print "$line\n";
}
</syntaxhighlight>
{{out}}
<pre style="height:35ex">A matrix
Line 3,597:
=={{header|Phix}}==
{{trans|Kotlin}}
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 3,674:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_Pause</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,710:
=={{header|PL/I}}==
<
LU_Decomposition: procedure options (main);
declare a1(3,3) float (18) initial ( 1, 3, 5,
Line 3,797:
end LU_Decomposition;
</syntaxhighlight>
Derived from Fortran version above.
Results:
Line 3,841:
=={{header|Python}}==
{{trans|D}}
<
def matrixMul(A, B):
Line 3,882:
for part in lu(b):
pprint(part)
print</
{{out}}
<pre>[[1.0, 0.0, 0.0],
Line 3,913:
=={{header|R}}==
<
A <- matrix(c(1, 3, 5, 2, 4, 7, 1, 1, 0), 3, 3, byrow=T)
dim(A) <- c(3, 3)
expand(lu(A))</
{{Out}}
Line 3,943:
=={{header|Racket}}==
<
#lang racket
(require math)
Line 3,959:
; #[0 -2 -3]
; #[0 0 -2]])
</syntaxhighlight>
=={{header|Raku}}==
Line 3,965:
Translation of Ruby.
<syntaxhighlight lang="raku"
[2, 4, 7],
[1, 1, 0]
Line 4,034:
say "\n$message";
$_».&rat-int.fmt("%7s").say for @array;
}</
{{out}}
<pre>A Matrix
Line 4,093:
=={{header|REXX}}==
<
#= 0; P.= 0; PA.= 0; L.= 0; U.= 0 /*initialize some variables to zero. */
parse arg x /*obtain matrix elements from the C.L. */
Line 4,154:
end /*c*/
say _
end /*r*/; return</
{{out|output|text= when using the input of: <tt> 1 3 5 2 4 7 1 1 0 </tt>}}
<pre>
Line 4,216:
=={{header|Ruby}}==
<
class Matrix
Line 4,280:
l.pretty_print(" %8.5f", "L")
u.pretty_print(" %8.5f", "U")
p.pretty_print(" %d", "P")</
{{out}}
Line 4,326:
Matrix has a <code>lup_decomposition</code> built-in method.
<
l.pretty_print(" %8.5f", "L")
u.pretty_print(" %8.5f", "U")
p.pretty_print(" %d", "P")</
Output is the same.
=={{header|Rust}}==
{{libheader| ndarray}}
<syntaxhighlight lang="rust">
#![allow(non_snake_case)]
use ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};
Line 4,421:
(L, U, P)
}
</syntaxhighlight>
Line 4,469:
=={{header|Sidef}}==
{{trans|Raku}}
<
func matrix_zero(n, m=n) { m.of { n.of(0) } }
func matrix_ident(n) { n.of {|i| n.of {|j| i==j ? 1 : 0 } } }
Line 4,542:
say_it(a, b)
}
}</
<pre style="height: 40ex; overflow: scroll">
A Matrix
Line 4,604:
See [http://www.stata.com/help.cgi?mf_lud LU decomposition] in Stata help.
<
: lud(a=(1,3,5\2,4,7\1,1,0),l=.,u=.,p=.)
Line 4,637:
2 | 1 |
3 | 3 |
+-----+</
=== Implementation ===
<
real scalar i,j,n,s
real vector js
Line 4,662:
u = uppertriangle(l)
l = lowertriangle(l, 1)
}</
'''Example''':
<
: a
Line 4,697:
2 | 1 |
3 | 3 |
+-----+</
=={{header|Tcl}}==
<
namespace eval matrix {
namespace path {::tcl::mathfunc ::tcl::mathop}
Line 4,767:
return $s
}
}</
Support code:
<
namespace eval matrix {
# Get the size of a matrix; assumes that all rows are the same length, which
Line 4,817:
return $max
}
}</
Demonstrating:
<
proc demo {A} {
lassign [matrix::luDecompose $A] L U P
Line 4,831:
demo {{1 3 5} {2 4 7} {1 1 0}}
puts "================================="
demo {{11 9 24 2} {1 5 2 6} {3 17 18 1} {2 5 7 1}}</
{{out}}
<pre>
Line 4,881:
=={{header|VBA}}==
{{trans|Phix}}
<
Private Function pivotize(m As Variant) As Variant
Dim n As Integer: n = UBound(m)
Line 4,975:
Debug.Print
Next i
End Sub</
<pre>== a,l,u,p: ==
1 3 5
Line 5,017:
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<
import "/fmt" for Fmt
Line 5,043:
Fmt.mprint(lup[2], 2, 0)
System.print()
}</
{{out}}
Line 5,102:
=={{header|zkl}}==
Using the GNU Scientific Library, which does the decomposition without returning the permutations:
<
fcn luTask(A){
A.LUDecompose(); // in place, contains L & U
Line 5,119:
2.0, 5.0, 7.0, 1.0);
L,U:=luTask(A);
println("L:\n",L.format(8,4),"\nU:\n",U.format(8,4));</
{{out}}
<pre>
Line 5,146:
A matrix is a list of lists, ie list of rows in row major order.
<
fcn eye(n){ // Creates a nxn identity matrix.
I:=make_array(n,n,0.0);
Line 5,195:
foreach i,j,k in (m,p,n){ ans[i][j]+=a[i][k]*b[k][j]; }
ans
}</
Example 1
<
lu(g).apply2("println");</
{{out}}
<pre>
Line 5,206:
</pre>
Example 2
<
L( 1.0, 5.0, 2.0, 6.0),
L( 3.0, 17.0, 18.0, 1.0),
Line 5,212:
fcn printM(m) { m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%9.5f "*row.len()).fmt(row.xplode()) }</
The list apply2 method is side effects only, it doesn't aggregate results. When given a list of actions, it applies the action and passes the result to the next action. The fpM method is partial application with a mask, "-" truncates the parameters at that point (in this case, no parameters, ie just print a blank line, not the result of printM).
{{out}}
|