LU decomposition: Difference between revisions
Content added Content deleted
m (→{{header|Tcl}}: Smarten up) |
(Simplified D code) |
||
Line 265: | Line 265: | ||
#2A((1 0 0 0) (0 0 1 0) (0 1 0 0) (0 0 0 1))</lang> |
#2A((1 0 0 0) (0 0 1 0) (0 1 0 0) (0 0 0 1))</lang> |
||
=={{header|D}}== |
=={{header|D}}== |
||
⚫ | |||
{{trans|Common Lisp}} |
|||
<lang d>import std.stdio, std.algorithm, std.typecons; |
<lang d>import std.stdio, std.algorithm, std.typecons; |
||
⚫ | |||
/// Creates a nxn identity matrix. |
/// Creates a nxn identity matrix. |
||
Line 280: | Line 281: | ||
return m; |
return m; |
||
} |
} |
||
/// Swap two rows l and k of a 2D array matrix m. |
|||
pure void swapRows(T)(ref T[][] m, const int l, const int k) { |
|||
swap(m[l], m[k]); |
|||
} |
|||
/// Creates the pivoting matrix for m. |
/// Creates the pivoting matrix for m. |
||
Line 298: | Line 294: | ||
T max = m[j][j]; |
T max = m[j][j]; |
||
int row = j; |
int row = j; |
||
foreach (i; j .. n) |
foreach (i; j .. n) |
||
if (m[i][j] > max) { |
if (m[i][j] > max) { |
||
max = m[i][j]; |
max = m[i][j]; |
||
row = i; |
row = i; |
||
} |
} |
||
} |
|||
if (j != row) |
if (j != row) |
||
swap(P[j], P[row]); |
|||
} |
} |
||
Line 334: | Line 329: | ||
s1 += U[k][j] * L[i][k]; |
s1 += U[k][j] * L[i][k]; |
||
U[i][j] = A2[i][j] - s1; |
U[i][j] = A2[i][j] - s1; |
||
} |
} |
||
foreach (i; j .. n) { |
foreach (i; j .. n) { |
||
Line 346: | Line 340: | ||
return tuple(L, U, P); |
return tuple(L, U, P); |
||
} |
} |
||
void main() { |
void main() { |
||
enum double[][] a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]; |
enum double[][] a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]; |
||
foreach (part; lu(a).tupleof) |
|||
writeln(prettyPrint( |
writeln(prettyPrint(part), "\n"); |
||
writeln(); |
|||
prettyPrint(lua[1]), "\n\n", |
|||
prettyPrint(lua[2]), "\n\n"); |
|||
enum double[][] b = [[11, 9, 24, 2], [1, 5, 2, 6], |
enum double[][] b = [[11, 9, 24, 2], [1, 5, 2, 6], |
||
[3, 17, 18, 1], [2, 5, 7, 1]]; |
[3, 17, 18, 1], [2, 5, 7, 1]]; |
||
foreach (part; lu(b).tupleof) |
|||
writeln(prettyPrint( |
writeln(prettyPrint(part), "\n"); |
||
prettyPrint(lub[1]), "\n\n", |
|||
prettyPrint(lub[2])); |
|||
}</lang> |
}</lang> |
||
Output: |
Output: |