LU decomposition: Difference between revisions

Content added Content deleted
m (Sort Mathematica < Python.)
(Updated D code, simplified, more const, shorter)
Line 589: Line 589:
std.array, std.conv;
std.array, std.conv;


bool isRectangular(T)(in T[][] m) pure nothrow {
bool isRectangular(T)(in T[][] m) pure /*nothrow*/ {
//return !canFind!((r){ return r.length != m[0].length; })(m);
return !canFind!((r){ return r.length != m[0].length; })(m);
foreach (row; m)
if (row.length != m[0].length)
return false;
return true;
}
}


bool isSquare(T)(in T[][] m) pure nothrow {
bool isSquare(T)(in T[][] m) pure /*nothrow*/ {
return isRectangular(m) && m[0].length == m.length;
return isRectangular(m) && m[0].length == m.length;
}
}


string prettyPrint(T)(in T[][] m) {
immutable(T[][]) matrixMul(T)(immutable T[][] A,
immutable T[][] B) pure nothrow
//return "[" ~ join(map!text(m), ",\n ") ~ "]";
return "[" ~ array(map!text(m)).join(",\n ") ~ "]";
}

T[][] matrixMul(T)(in T[][] A, in T[][] B) pure nothrow
in {
in {
assert(A.length && B.length &&
assert(A.length && B.length &&
Line 639: Line 631:


/// Creates the pivoting matrix for m.
/// Creates the pivoting matrix for m.
T[][] pivotize(T)(in T[][] m) pure nothrow
immutable(T[][]) pivotize(T)(immutable T[][] m) pure nothrow
in {
in {
assert(isSquare(m));
assert(isSquare(m));
Line 663: Line 655:
/// Decomposes a square matrix A by PA=LU and returns L, U and P.
/// Decomposes a square matrix A by PA=LU and returns L, U and P.
Tuple!(T[][],"L", T[][],"U", const T[][],"P")
Tuple!(T[][],"L", T[][],"U", const T[][],"P")
lu(T)(in T[][] A) pure nothrow
lu(T)(immutable T[][] A) pure nothrow
in {
in {
assert(isSquare(A));
assert(isSquare(A));
Line 675: Line 667:
}
}


/*immutable*/ const P = pivotize!T(A);
immutable P = pivotize!T(A);
/*immutable*/ const A2 = matrixMul!T(P, A);
immutable A2 = matrixMul!T(P, A);


foreach (j; 0 .. n) {
foreach (j; 0 .. n) {
Line 698: Line 690:


void main() {
void main() {
enum double[][] a = [[1, 3, 5],
immutable a = [[1., 3, 5],
[2, 4, 7],
[2., 4, 7],
[1, 1, 0]];
[1., 1, 0]];
foreach (part; lu(a).tupleof)
foreach (part; lu(a))
writeln(prettyPrint(part), "\n");
writeln("[", join(map!text(part), ",\n "), "]\n");
writeln();
writeln();


enum double[][] b = [[11, 9, 24, 2],
immutable b = [[11., 9, 24, 2],
[1, 5, 2, 6],
[1., 5, 2, 6],
[3, 17, 18, 1],
[3., 17, 18, 1],
[2, 5, 7, 1]];
[2., 5, 7, 1]];
foreach (part; lu(b).tupleof)
foreach (part; lu(b))
writeln(prettyPrint(part), "\n");
writeln("[", join(map!text(part), ",\n "), "]\n");
}</lang>
}</lang>
Output:
Output:
Line 739: Line 731:
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]]</pre>
[0, 0, 0, 1]]
</pre>

=={{header|Go}}==
=={{header|Go}}==
{{trans|Common Lisp}}
{{trans|Common Lisp}}