Cholesky decomposition: Difference between revisions

Content added Content deleted
m (Added Delphi reference to Pascal code)
(Updated to work with version 1.4 of Nim. Improved output formatting. Added a generic type Matrix.)
Line 2,210: Line 2,210:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|C}}
{{trans|C}}
<lang nim>import math, strutils
<lang nim>import math, strutils, strformat


type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]
proc cholesky[T](a: T): T =

for i in 0 .. < a[0].len:
proc cholesky[Matrix](a: Matrix): Matrix =
for i in 0 ..< a[0].len:
for j in 0 .. i:
for j in 0 .. i:
var s = 0.0
var s = 0.0
for k in 0 .. < j:
for k in 0 ..< j:
s += result[i][k] * result[j][k]
s += result[i][k] * result[j][k]
result[i][j] = if i == j: sqrt(a[i][i]-s)
result[i][j] = if i == j: sqrt(a[i][i]-s)
else: (1.0 / result[j][j] * (a[i][j] - s))
else: 1.0 / result[j][j] * (a[i][j] - s)


proc `$`(a): string =
proc `$`(a: Matrix): string =
result = ""
result = ""
for b in a:
for b in a:
var line = ""
for c in b:
for c in b:
line.addSep(" ", 0)
result.add c.formatFloat(ffDecimal, 5) & " "
result.add "\n"
line.add fmt"{c:8.5f}"
result.add line & '\n'


let m1 = [[25.0, 15.0, -5.0],
let m1 = [[25.0, 15.0, -5.0],
Line 2,238: Line 2,242:
[42.0, 62.0, 134.0, 106.0]]
[42.0, 62.0, 134.0, 106.0]]
echo cholesky(m2)</lang>
echo cholesky(m2)</lang>
Output:
<pre>5.00000 0.00000 0.00000
3.00000 3.00000 0.00000
-1.00000 1.00000 3.00000


{{out}}
4.24264 0.00000 0.00000 0.00000
5.18545 6.56591 0.00000 0.00000
<pre> 5.00000 0.00000 0.00000
12.72792 3.04604 1.64974 0.00000
3.00000 3.00000 0.00000
-1.00000 1.00000 3.00000
9.89949 1.62455 1.84971 1.39262</pre>

4.24264 0.00000 0.00000 0.00000
5.18545 6.56591 0.00000 0.00000
12.72792 3.04604 1.64974 0.00000
9.89949 1.62455 1.84971 1.39262</pre>


=={{header|Objeck}}==
=={{header|Objeck}}==