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); |
|||
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; |
||
} |
} |
||
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)( |
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)( |
lu(T)(immutable T[][] A) pure nothrow |
||
in { |
in { |
||
assert(isSquare(A)); |
assert(isSquare(A)); |
||
Line 675: | Line 667: | ||
} |
} |
||
immutable P = pivotize!T(A); |
|||
immutable A2 = matrixMul!T(P, A); |
|||
foreach (j; 0 .. n) { |
foreach (j; 0 .. n) { |
||
Line 698: | Line 690: | ||
void main() { |
void main() { |
||
immutable a = [[1., 3, 5], |
|||
[2., 4, 7], |
|||
[1., 1, 0]]; |
|||
foreach (part; lu(a) |
foreach (part; lu(a)) |
||
writeln( |
writeln("[", join(map!text(part), ",\n "), "]\n"); |
||
writeln(); |
writeln(); |
||
immutable b = [[11., 9, 24, 2], |
|||
[1., 5, 2, 6], |
|||
[3., 17, 18, 1], |
|||
[2., 5, 7, 1]]; |
|||
foreach (part; lu(b) |
foreach (part; lu(b)) |
||
writeln( |
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]] |
[0, 0, 0, 1]] |
||
</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |