Cholesky decomposition: Difference between revisions

m
(→‎{{header|Scilab}}: left as LaTeX, if someone knows why the math tag fails, I'll be happy to be informed)
m (→‎{{header|Wren}}: Minor tidy)
 
(43 intermediate revisions by 26 users not shown)
Line 77:
;Note:
# The Cholesky decomposition of a [[Pascal matrix generation‎|Pascal]] upper-triangle matrix is the [[wp:Identity matrix|Identity matrix]] of the same size.
# The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F cholesky(A)
V l = [[0.0] * A.len] * A.len
L(i) 0 .< A.len
L(j) 0 .. i
V s = sum((0 .< j).map(k -> @l[@i][k] * @l[@j][k]))
l[i][j] = I (i == j) {sqrt(A[i][i] - s)} E (1.0 / l[j][j] * (A[i][j] - s))
R l
 
F pprint(m)
print(‘[’)
L(row) m
print(row)
print(‘]’)
 
V m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
print(cholesky(m1))
print()
 
V m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2))</syntaxhighlight>
 
{{out}}
<pre>
[[5, 0, 0], [3, 3, 0], [-1, 1, 3]]
 
[
[4.24264, 0, 0, 0]
[5.18545, 6.56591, 0, 0]
[12.7279, 3.04604, 1.64974, 0]
[9.89949, 1.62455, 1.84971, 1.39262]
]
</pre>
=={{header|Ada}}==
{{works with|Ada 2005}}
decomposition.ads:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Generic_Real_Arrays;
generic
with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);
Line 91 ⟶ 129:
procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix);
 
end Decomposition;</langsyntaxhighlight>
 
decomposition.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Generic_Elementary_Functions;
 
package body Decomposition is
Line 126 ⟶ 164:
end loop;
end Decompose;
end Decomposition;</langsyntaxhighlight>
 
Example usage:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Real_Arrays;
with Ada.Text_IO;
with Decomposition;
Line 173 ⟶ 211:
Ada.Text_IO.Put_Line ("A:"); Print (Example_2);
Ada.Text_IO.Put_Line ("L:"); Print (L_2);
end Decompose_Example;</langsyntaxhighlight>
{{out}}
<pre>Example 1:
Line 196 ⟶ 234:
12.728 3.046 1.650 0.000
9.899 1.625 1.850 1.393</pre>
 
=={{header|ALGOL 68}}==
{{trans|C}} Note: This specimen retains the original [[#C|C]] coding style. [http://rosettacode.org/mw/index.php?title=Cholesky_decomposition&action=historysubmit&diff=107753&oldid=107752 diff]
Line 202 ⟶ 239:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
MODE FIELD=LONG REAL;
Line 260 ⟶ 297:
MAT c2 = cholesky(m2);
print matrix(c2)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 271 ⟶ 308:
( 9.89949, 1.62455, 1.84971, 1.39262))
</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">cholesky: function [m][
result: array.of: @[size m, size m] 0.0
 
loop 0..dec size m\0 'i [
loop 0..i 'j [
s: 0.0
loop 0..j 'k ->
s: s + result\[i]\[k] * result\[j]\[k]
 
result\[i]\[j]: (i = j)? -> sqrt m\[i]\[i] - s
-> (1.0 // result\[j]\[j]) * (m\[i]\[j] - s)
]
]
return result
]
 
printMatrix: function [a]->
loop a 'b ->
print to [:string] .format:"8.5f" b
 
m1: @[
@[25.0, 15.0, neg 5.0]
@[15.0, 18.0, 0.0]
@[neg 5.0, 0.0, 11.0]
]
printMatrix cholesky m1
 
print ""
 
m2: [
[18.0, 22.0, 54.0, 42.0]
[22.0, 70.0, 86.0, 62.0]
[54.0, 86.0, 174.0, 134.0]
[42.0, 62.0, 134.0, 106.0]
]
printMatrix cholesky m2</syntaxhighlight>
 
{{out}}
 
<pre> 5.00000 0.00000 0.00000
3.00000 3.00000 0.00000
-1.00000 1.00000 3.00000
 
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|ATS}}==
<syntaxhighlight lang="ats">
%{^
#include <math.h>
#include <float.h>
%}
 
#include "share/atspre_staload.hats"
 
macdef NAN = g0f2f ($extval (float, "NAN"))
macdef Zero = g0i2f 0
macdef One = g0i2f 1
 
(* The sqrt(3) function made part of the ‘g0float’ typekind series.
(The ats2-xprelude package will do this for you, but it is easy
to do if you are not using a lot of math functions. *)
extern fn {tk : tkind} g0float_sqrt : g0float tk -<> g0float tk
overload sqrt with g0float_sqrt
implement g0float_sqrt<fltknd> x = $extfcall (float, "sqrtf", x)
implement g0float_sqrt<dblknd> x = $extfcall (double, "sqrt", x)
implement g0float_sqrt<ldblknd> x = $extfcall (ldouble, "sqrtl", x)
 
(*------------------------------------------------------------------*)
(* A "very little matrix library" *)
 
typedef Matrix_Index_Map (m1 : int, n1 : int, m0 : int, n0 : int) =
{i1, j1 : pos | i1 <= m1; j1 <= n1}
(int i1, int j1) -<cloref0>
[i0, j0 : pos | i0 <= m0; j0 <= n0]
@(int i0, int j0)
 
datatype Real_Matrix (tk : tkind,
m1 : int, n1 : int,
m0 : int, n0 : int) =
| Real_Matrix of (matrixref (g0float tk, m0, n0),
int m1, int n1, int m0, int n0,
Matrix_Index_Map (m1, n1, m0, n0))
typedef Real_Matrix (tk : tkind, m1 : int, n1 : int) =
[m0, n0 : pos] Real_Matrix (tk, m1, n1, m0, n0)
typedef Real_Vector (tk : tkind, m1 : int, n1 : int) =
[m1 == 1 || n1 == 1] Real_Matrix (tk, m1, n1)
typedef Real_Row (tk : tkind, n1 : int) = Real_Vector (tk, 1, n1)
typedef Real_Column (tk : tkind, m1 : int) = Real_Vector (tk, m1, 1)
 
extern fn {tk : tkind}
Real_Matrix_make_elt :
{m0, n0 : pos}
(int m0, int n0, g0float tk) -< !wrt >
Real_Matrix (tk, m0, n0, m0, n0)
 
extern fn {tk : tkind}
Real_Matrix_copy :
{m1, n1 : pos}
Real_Matrix (tk, m1, n1) -< !refwrt > Real_Matrix (tk, m1, n1)
 
extern fn {tk : tkind}
Real_Matrix_copy_to :
{m1, n1 : pos}
(Real_Matrix (tk, m1, n1), (* destination *)
Real_Matrix (tk, m1, n1)) -< !refwrt >
void
 
extern fn {}
Real_Matrix_dimension :
{tk : tkind}
{m1, n1 : pos}
Real_Matrix (tk, m1, n1) -<> @(int m1, int n1)
 
extern fn {tk : tkind}
Real_Matrix_get_at :
{m1, n1 : pos}
{i1, j1 : pos | i1 <= m1; j1 <= n1}
(Real_Matrix (tk, m1, n1), int i1, int j1) -< !ref > g0float tk
 
extern fn {tk : tkind}
Real_Matrix_set_at :
{m1, n1 : pos}
{i1, j1 : pos | i1 <= m1; j1 <= n1}
(Real_Matrix (tk, m1, n1), int i1, int j1, g0float tk) -< !refwrt >
void
 
extern fn {}
Real_Matrix_reflect_lower_triangle :
(* This operation makes every It is a change in how INDEXING
works. All the storage is still in the lower triangle. *)
{tk : tkind}
{n1 : pos}
{m0, n0 : pos}
Real_Matrix (tk, n1, n1, m0, n0) -<>
Real_Matrix (tk, n1, n1, m0, n0)
 
extern fn {tk : tkind}
Real_Matrix_fprint :
{m, n : pos}
(FILEref, Real_Matrix (tk, m, n)) -<1> void
 
overload copy with Real_Matrix_copy
overload copy_to with Real_Matrix_copy_to
overload dimension with Real_Matrix_dimension
overload [] with Real_Matrix_get_at
overload [] with Real_Matrix_set_at
overload reflect_lower_triangle with
Real_Matrix_reflect_lower_triangle
 
(*------------------------------------------------------------------*)
(* Implementation of the "very little matrix library" *)
 
implement {tk}
Real_Matrix_make_elt (m0, n0, elt) =
Real_Matrix (matrixref_make_elt<g0float tk> (i2sz m0, i2sz n0, elt),
m0, n0, m0, n0, lam (i1, j1) => @(i1, j1))
 
implement {}
Real_Matrix_dimension A =
case+ A of Real_Matrix (_, m1, n1, _, _, _) => @(m1, n1)
 
implement {tk}
Real_Matrix_get_at (A, i1, j1) =
let
val+ Real_Matrix (storage, _, _, _, n0, index_map) = A
val @(i0, j0) = index_map (i1, j1)
in
matrixref_get_at<g0float tk> (storage, pred i0, n0, pred j0)
end
 
implement {tk}
Real_Matrix_set_at (A, i1, j1, x) =
let
val+ Real_Matrix (storage, _, _, _, n0, index_map) = A
val @(i0, j0) = index_map (i1, j1)
in
matrixref_set_at<g0float tk> (storage, pred i0, n0, pred j0, x)
end
 
implement {}
Real_Matrix_reflect_lower_triangle {..} {n1} A =
let
typedef t = intBtwe (1, n1)
val+ Real_Matrix (storage, n1, _, m0, n0, index_map) = A
in
Real_Matrix (storage, n1, n1, m0, n0,
lam (i, j) =>
index_map ((if j <= i then i else j) : t,
(if j <= i then j else i) : t))
end
 
implement {tk}
Real_Matrix_copy A =
let
val @(m1, n1) = dimension A
val C = Real_Matrix_make_elt<tk> (m1, n1, A[1, 1])
val () = copy_to<tk> (C, A)
in
C
end
 
implement {tk}
Real_Matrix_copy_to (Dst, Src) =
let
val @(m1, n1) = dimension Src
prval [m1 : int] EQINT () = eqint_make_gint m1
prval [n1 : int] EQINT () = eqint_make_gint n1
 
var i : intGte 1
in
for* {i : pos | i <= m1 + 1} .<(m1 + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m1; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n1 + 1} .<(n1 + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n1; j := succ j)
Dst[i, j] := Src[i, j]
end
end
 
implement {tk}
Real_Matrix_fprint {m, n} (outf, A) =
let
val @(m, n) = dimension A
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n; j := succ j)
let
typedef FILEstar = $extype"FILE *"
extern castfn FILEref2star : FILEref -<> FILEstar
val _ = $extfcall (int, "fprintf", FILEref2star outf,
"%16.6g", A[i, j])
in
end;
fprintln! (outf)
end
end
 
(*------------------------------------------------------------------*)
(* Cholesky-Banachiewicz, in place. See
https://en.wikipedia.org/w/index.php?title=Cholesky_decomposition&oldid=1149960985#The_Cholesky%E2%80%93Banachiewicz_and_Cholesky%E2%80%93Crout_algorithms
 
I would use Cholesky-Crout if my matrices were stored in column
major order. But it makes little difference. *)
 
extern fn {tk : tkind}
Real_Matrix_cholesky_decomposition :
(* Only the lower triangle is considered. *)
{n : pos}
Real_Matrix (tk, n, n) -< !refwrt > void
 
overload cholesky_decomposition with
Real_Matrix_cholesky_decomposition
 
implement {tk}
Real_Matrix_cholesky_decomposition {n} A =
let
val @(n, _) = dimension A
 
(* I arrange the nested loops somewhat differently from how it is
done in the Wikipedia article's C snippet. *)
fun
repeat {i, j : pos | j <= i; i <= n + 1} (* <-- allowed values *)
.<(n + 1) - i, i - j>. (* <-- proof of termination *)
(i : int i, j : int j) :<!refwrt> void =
if i = n + 1 then
() (* All done. *)
else
let
fun
_sum {k : pos | k <= j} .<j - k>.
(x : g0float tk, k : int k) :<!refwrt> g0float tk =
if k = j then
x
else
_sum (x + (A[i, k] * A[j, k]), succ k)
 
val sum = _sum (Zero, 1)
in
if j = i then
begin
A[i, j] := sqrt (A[i, i] - sum);
repeat (succ i, 1)
end
else
begin
A[i, j] := (One / A[j, j]) * (A[i, j] - sum);
repeat (i, succ j)
end
end
in
repeat (1, 1)
end
 
(*------------------------------------------------------------------*)
 
fn {tk : tkind} (* We like Fortran, so COLUMN major here. *)
column_major_list_to_square_matrix
{n : pos}
(n : int n,
lst : list (g0float tk, n * n))
: Real_Matrix (tk, n, n) =
let
#define :: list_cons
prval () = mul_gte_gte_gte {n, n} ()
val A = Real_Matrix_make_elt (n, n, NAN)
val lstref : ref (List0 (g0float tk)) = ref lst
var j : intGte 1
in
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n; j := succ j)
let
var i : intGte 1
in
for* {i : pos | i <= n + 1} .<(n + 1) - i>.
(i : int i) =>
(i := 1; i <> succ n; i := succ i)
case- !lstref of
| hd :: tl =>
begin
A[i, j] := hd;
!lstref := tl
end
end;
A
end
 
implement
main0 () =
let
val _A =
column_major_list_to_square_matrix
(3, $list (25.0, 15.0, ~5.0,
0.0, 18.0, 0.0,
0.0, 0.0, 11.0))
val A = reflect_lower_triangle _A
and B = copy _A
val () =
begin
cholesky_decomposition B;
print! ("\nThe Cholesky decomposition of\n\n");
Real_Matrix_fprint (stdout_ref, A);
print! ("is\n");
Real_Matrix_fprint (stdout_ref, B)
end
 
val _A =
column_major_list_to_square_matrix
(4, $list (18.0, 22.0, 54.0, 42.0,
0.0, 70.0, 86.0, 62.0,
0.0, 0.0, 174.0, 134.0,
0.0, 0.0, 0.0, 106.0))
val A = reflect_lower_triangle _A
and B = copy _A
val () =
begin
cholesky_decomposition B;
print! ("\nThe Cholesky decomposition of\n\n");
Real_Matrix_fprint (stdout_ref, A);
print! ("is\n");
Real_Matrix_fprint (stdout_ref, B)
end
in
println! ()
end
 
(*------------------------------------------------------------------*)
</syntaxhighlight>
 
{{out}}
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_GCBDW cholesky_decomposition_task.dats -lgc -lm && ./a.out
 
The Cholesky decomposition of
 
25 15 -5
15 18 0
-5 0 11
is
5 0 0
3 3 0
-1 1 3
 
The Cholesky decomposition of
 
18 22 54 42
22 70 86 62
54 86 174 134
42 62 134 106
is
4.24264 0 0 0
5.18545 6.56591 0 0
12.7279 3.04604 1.64974 0
9.89949 1.62455 1.84971 1.39262
 
</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Cholesky_Decomposition(A){
L := [], n := A.Count()
L[1,1] := Sqrt(A[1,1])
loop % n {
k := A_Index
loop % n-1 {
i := A_Index+1
Sigma := 0, j := 0
while (++j <= k-1)
Sigma += L[i, j] * L[k, j]
L[i, k] := (A[i, k] - Sigma) / L[k, k]
Sigma := 0, j := 0
while (++j <= k-1)
Sigma += (L[k, j])**2
L[k, k] := Sqrt(A[k, k] - Sigma)
}
}
loop % n{
k := A_Index
loop % n
L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0
}
return L
}
ShowMatrix(L){
for r, obj in L{
row := ""
for c, v in obj
row .= Format("{:.3f}", v) ", "
output .= "[" trim(row, ", ") "]`n,"
}
return "[" Trim(output, "`n,") "]"
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">A := [[25, 15, -5]
, [15, 18, 0]
, [-5, 0 , 11]]
L1 := Cholesky_Decomposition(A)
 
A := [[18, 22, 54, 42]
, [22, 70, 86, 62]
, [54, 86, 174, 134]
, [42, 62, 134, 106]]
L2 := Cholesky_Decomposition(A)
 
MsgBox % Result := ShowMatrix(L1) "`n----`n" ShowMatrix(L2) "`n----"
return</syntaxhighlight>
{{out}}
<pre>[[5.000, 0.000, 0.000]
,[3.000, 3.000, 0.000]
,[-1.000, 1.000, 3.000]]
----
[[4.243, 0.000, 0.000, 0.000]
,[5.185, 6.566, 0.000, 0.000]
,[12.728, 3.046, 1.650, 0.000]
,[9.899, 1.625, 1.850, 1.393]]
----</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM m1(2,2)
m1() = 25, 15, -5, \
\ 15, 18, 0, \
Line 319 ⟶ 828:
PRINT
NEXT row%
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 331 ⟶ 840:
9.89949 1.62455 1.84971 1.39262
</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 383 ⟶ 891:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>5.00000 0.00000 0.00000
Line 393 ⟶ 901:
12.72792 3.04604 1.64974 0.00000
9.89949 1.62455 1.84971 1.39262</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
<lang [C sharp|C#]>
using System;
using System.Collections.Generic;
using System.Linq;
Line 498 ⟶ 1,004:
}
}
}</syntaxhighlight>
}
 
</lang>
{{out}}
Test 1:
Line 526 ⟶ 1,031:
12.72792, 3.04604, 1.64974, 0.00000,
9.89949, 1.62455, 1.84971, 1.39262,
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
 
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
 
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
 
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
 
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
 
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
 
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
 
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
 
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
 
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
 
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
Matrix:
25.00000 15.00000 -5.00000
15.00000 18.00000 0.00000
-5.00000 0.00000 11.00000
Cholesky factor:
5.00000 0.00000 0.00000
3.00000 3.00000 0.00000
-1.00000 1.00000 3.00000
Matrix:
18.00000 22.00000 54.00000 42.00000
22.00000 70.00000 86.00000 62.00000
54.00000 86.00000 174.00000 134.00000
42.00000 62.00000 134.00000 106.00000
Cholesky factor:
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|Clojure}}==
{{trans|Python}}
<langsyntaxhighlight lang="clojure">(defn cholesky
[matrix]
(let [n (count matrix)
Line 540 ⟶ 1,168:
(Math/sqrt (- (aget A i i) s))
(* (/ 1.0 (aget L j j)) (- (aget A i j) s))))))
(vec (map vec L))))</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="clojure">(cholesky [[25 15 -5] [15 18 0] [-5 0 11]])
;=> [[ 5.0 0.0 0.0]
; [ 3.0 3.0 0.0]
Line 551 ⟶ 1,179:
; [ 5.185449728701349 6.565905201197403 0.0 0.0 ]
; [12.727922061357857 3.0460384954008553 1.6497422479090704 0.0 ]
; [ 9.899494936611667 1.624553864213788 1.8497110052313648 1.3926212476456026]]</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">;; Calculates the Cholesky decomposition matrix L
;; for a positive-definite, symmetric nxn matrix A.
(defun chol (A)
Line 582 ⟶ 1,209:
 
;; Return the calculated matrix L.
L))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">;; Example 1:
(setf A (make-array '(3 3) :initial-contents '((25 15 -5) (15 18 0) (-5 0 11))))
(chol A)
#2A((5.0 0 0)
(3.0 3.0 0)
(-1.0 1.0 3.0))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">;; Example 2:
(setf B (make-array '(4 4) :initial-contents '((18 22 54 42) (22 70 86 62) (54 86 174 134) (42 62 134 106))))
(chol B)
Line 597 ⟶ 1,224:
(5.18545 6.565905 0 0)
(12.727922 3.0460374 1.6497375 0)
(9.899495 1.6245536 1.849715 1.3926151))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">;; case of matrix stored as a list of lists (inner lists are rows of matrix)
;; as above, returns the Cholesky decomposition matrix of a square positive-definite, symmetric matrix
(defun cholesky (m)
Line 609 ⟶ 1,236:
(setf (cdr (last l)) (list (nconc x (list (sqrt (- (elt cm (incf j)) (*v x x))))))))))
;; where *v is the scalar product defined as
(defun *v (v1 v2) (reduce #'+ (mapcar #'* v1 v2)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">;; example 1
CL-USER> (setf a '((25 15 -5) (15 18 0) (-5 0 11)))
((25 15 -5) (15 18 0) (-5 0 11))
Line 620 ⟶ 1,247:
3 3 0
-1 1 3
NIL</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">;; example 2
CL-USER> (setf a '((18 22 54 42) (22 70 86 62) (54 86 174 134) (42 62 134 106)))
((18 22 54 42) (22 70 86 62) (54 86 174 134) (42 62 134 106))
Line 632 ⟶ 1,259:
12.72792 3.04604 1.64974 0.00000
9.89950 1.62455 1.84971 1.39262
NIL</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.numeric;
 
T[][] cholesky(T)(in T[][] A) pure nothrow /*@safe*/ {
Line 661 ⟶ 1,287:
[42, 62, 134, 106]];
writefln("%(%(%2.3f %)\n%)", m2.cholesky);
}</langsyntaxhighlight>
{{out}}
<pre> 5 0 0
Line 671 ⟶ 1,297:
12.728 3.046 1.650 0.000
9.899 1.625 1.850 1.393</pre>
=={{header|Delphi}}==
 
See [[#Pascal|Pascal]].
=={{header|DWScript}}==
{{Trans|C}}
<langsyntaxhighlight lang="delphi">function Cholesky(a : array of Float) : array of Float;
var
i, j, k, n : Integer;
Line 719 ⟶ 1,346:
42.0, 62.0, 134.0, 106.0 ];
var c2 := Cholesky(m2);
ShowMatrix(c2);</langsyntaxhighlight>
=={{header|F_Sharp|F#}}==
 
<syntaxhighlight lang="fsharp">open Microsoft.FSharp.Collections
 
let cholesky a =
let calc (a: float[,]) (l: float[,]) i j =
let c1 j =
let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1]
sqrt (a.[j, j] - sum)
let c2 i j =
let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1]
(1.0 / l.[j, j]) * (a.[i, j] - sum)
if j > i then 0.0 else
if i = j
then c1 j
else c2 i j
let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a)
Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l
l
 
let printMat a =
let arrow = (Array2D.length2 a |> float) / 2.0 |> int
let c = cholesky a
for row in 0..(Array2D.length1 a) - 1 do
for col in 0..(Array2D.length2 a) - 1 do
printf "%.5f,\t" a.[row, col]
printf (if arrow = row then "--> \t" else "\t\t")
for col in 0..(Array2D.length2 c) - 1 do
printf "%.5f,\t" c.[row, col]
printfn ""
 
let ex1 = array2D [
[25.0; 15.0; -5.0];
[15.0; 18.0; 0.0];
[-5.0; 0.0; 11.0]]
 
let ex2 = array2D [
[18.0; 22.0; 54.0; 42.0];
[22.0; 70.0; 86.0; 62.0];
[54.0; 86.0; 174.0; 134.0];
[42.0; 62.0; 134.0; 106.0]]
 
printfn "ex1:"
printMat ex1
 
printfn "ex2:"
printMat ex2
</syntaxhighlight>
{{out}}
<pre>ex1:
25.00000, 15.00000, -5.00000, 5.00000, 0.00000, 0.00000,
15.00000, 18.00000, 0.00000, --> 3.00000, 3.00000, 0.00000,
-5.00000, 0.00000, 11.00000, -1.00000, 1.00000, 3.00000,
ex2:
18.00000, 22.00000, 54.00000, 42.00000, 4.24264, 0.00000, 0.00000, 0.00000,
22.00000, 70.00000, 86.00000, 62.00000, 5.18545, 6.56591, 0.00000, 0.00000,
54.00000, 86.00000, 174.00000, 134.00000, --> 12.72792, 3.04604, 1.64974, 0.00000,
42.00000, 62.00000, 134.00000, 106.00000, 9.89949, 1.62455, 1.84971, 1.39262,
</pre>
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">**
** Cholesky decomposition
**
Line 776 ⟶ 1,461:
runTest ([[18f,22f,54f,42f],[22f,70f,86f,62f],[54f,86f,174f,134f],[42f,62f,134f,106f]])
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 784 ⟶ 1,469:
[[4.242640687119285, 0.0, 0.0, 0.0], [5.185449728701349, 6.565905201197403, 0.0, 0.0], [12.727922061357857, 3.0460384954008553, 1.6497422479090704, 0.0], [9.899494936611667, 1.624553864213788, 1.8497110052313648, 1.3926212476456026]]
</pre>
 
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">Program Cholesky_decomp
! *************************************************!
! LBH @ ULPGC 06/03/2014
Line 856 ⟶ 1,539:
end do
 
End program Cholesky_decomp</lang syntaxhighlight>
{{out}}
<pre>
Line 865 ⟶ 1,548:
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="freebasic">' version 18-01-2017
' compile with: fbc -s console
 
Line 930 ⟶ 1,613:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> 5.00000 0.00000 0.00000
Line 940 ⟶ 1,623:
12.72792 3.04604 1.64974 0.00000
9.89949 1.62455 1.84971 1.39262</pre>
 
=={{header|Frink}}==
Frink's package [https://frinklang.org/fsp/colorize.fsp?f=Matrix.frink Matrix.frink] contains routines for Cholesky-Crout decomposition of a square Hermitian matrix (which can be real or complex.) This code is adapted from that more powerful class to work on raw 2-dimensional arrays. This also demonstrates Frink's layout routines.
 
<syntaxhighlight lang="frink">Cholesky[array] :=
{
n = length[array]
L = new array[[n,n], 0]
 
for j = 0 to n-1
{
sum = 0
for k = 0 to j-1
sum = sum + (L@j@k)^2
 
L@j@j = sqrt[array@j@j - sum]
 
for i = j+1 to n-1
{
sum = 0
for k = 0 to j-1
sum = sum + L@i@k * L@j@k
 
L@i@j = (1 / L@j@j * (array@i@j -sum))
}
}
 
return L
}
 
A = [[ 25, 15, -5],
[ 15, 18, 0],
[ -5, 0, 11]]
 
println[formatTable[[[formatMatrix[A], "->", formatMatrix[Cholesky[A]]]]]]
 
B = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
 
println[formatTable[[[formatMatrix[B], "->", formatMatrix[formatFix[Cholesky[B], 1, 5]]]]]]</syntaxhighlight>
{{out}}
<pre>
┌ ┐ ┌ ┐
│25 15 -5│ │ 5 0 0│
│ │ │ │
│15 18 0│ -> │ 3 3 0│
│ │ │ │
│-5 0 11│ │-1 1 3│
└ ┘ └ ┘
┌ ┐ ┌ ┐
│18 22 54 42│ │ 4.24264 0.00000 0.00000 0.00000│
│ │ │ │
│22 70 86 62│ │ 5.18545 6.56591 0.00000 0.00000│
│ │ -> │ │
│54 86 174 134│ │12.72792 3.04604 1.64974 0.00000│
│ │ │ │
│42 62 134 106│ │ 9.89949 1.62455 1.84971 1.39262│
└ ┘ └ ┘
</pre>
 
=={{header|Go}}==
===Real===
This version works with real matrices, like most other solutions on the page. The representation is packed, however, storing only the lower triange of the input symetric matrix and the output lower matrix. The decomposition algorithm computes rows in order from top to bottom but is a little different thatn Cholesky–Banachiewicz.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,048 ⟶ 1,792:
fmt.Println("L:")
a.choleskyLower().print()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,072 ⟶ 1,816:
===Hermitian===
This version handles complex Hermitian matricies as described on the WP page. The matrix representation is flat, and storage is allocated for all elements, not just the lower triangles. The decomposition algorithm is Cholesky–Banachiewicz.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,146 ⟶ 1,890:
a.print(heading)
a.choleskyDecomp().print("Cholesky factor L:")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,180 ⟶ 1,924:
</pre>
 
===Library gonum/matrixmat===
<langsyntaxhighlight lang="go">package main
 
import (
"fmt"
 
"githubgonum.comorg/gonumv1/matrixgonum/mat64mat"
)
 
func cholesky(order int, elements []float64) fmt.Formatter {
var c mat.Cholesky
t := mat64.NewTriDense(order, false, nil)
tc.CholeskyFactorize(mat64mat.NewSymDense(order, elements), false)
return mat64mat.Formatted(tc.LTo(nil))
}
 
Line 1,207 ⟶ 1,951:
42, 62, 134, 106,
}))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,221 ⟶ 1,965:
 
===Library go.matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,253 ⟶ 1,997:
fmt.Println("L:")
fmt.Println(l)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,275 ⟶ 2,019:
9.899495, 1.624554, 1.849711, 1.392621}
</pre>
=={{header|Groovy}}==
{{Trans|Java}}
<syntaxhighlight lang="groovy">def decompose = { a ->
assert a.size > 0 && a[0].size == a.size
def m = a.size
def l = [].withEagerDefault { [].withEagerDefault { 0 } }
(0..<m).each { i ->
(0..i).each { k ->
Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0
l[i][k] = (i == k)
? Math.sqrt(a[i][i] - s)
: (1.0 / l[k][k] * (a[i][k] - s))
}
}
l
}</syntaxhighlight>
Test:
<syntaxhighlight lang="groovy">def test1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
 
def test2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]];
 
[test1,test2]. each { test ->
println()
decompose(test).each { println it[0..<(test.size)] }
}</syntaxhighlight>
{{out}}
<pre>[5.0, 0, 0]
[3.0, 3.0, 0]
[-1.0, 1.0, 3.0]
 
[4.242640687119285, 0, 0, 0]
[5.185449728701349, 6.565905201197403, 0, 0]
[12.727922061357857, 3.0460384954008553, 1.6497422479090704, 0]
[9.899494936611667, 1.624553864213788, 1.8497110052313648, 1.3926212476456026]</pre>
=={{header|Haskell}}==
We use the [http://en.wikipedia.org/wiki/Cholesky_decomposition#The_Cholesky.E2.80.93Banachiewicz_and_Cholesky.E2.80.93Crout_algorithms Cholesky–Banachiewicz algorithm] described in the Wikipedia article.
Line 1,282 ⟶ 2,064:
 
The Cholesky module:
<langsyntaxhighlight lang="haskell">module Cholesky (Arr, cholesky) where
 
import Data.Array.IArray
Line 1,310 ⟶ 2,092:
return l
where maxBnd = fst . snd . bounds
update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)</langsyntaxhighlight>
The main module:
<langsyntaxhighlight lang="haskell">import Data.Array.IArray
import Data.List
import Cholesky
Line 1,341 ⟶ 2,123:
main = do
putStrLn $ showMatrice 3 $ elems $ cholesky ex1
putStrLn $ showMatrice 4 $ elems $ cholesky ex2</langsyntaxhighlight>
<b>output:</b>
<pre>
Line 1,353 ⟶ 2,135:
</pre>
 
===With Numeric.LinearAlgebra===
<syntaxhighlight lang="haskell">import Numeric.LinearAlgebra
 
a,b :: Matrix R
a = (3><3)
[25, 15, -5
,15, 18, 0
,-5, 0, 11]
 
b = (4><4)
[ 18, 22, 54, 42
, 22, 70, 86, 62
, 54, 86,174,134
, 42, 62,134,106]
 
main = do
let sa = sym a
sb = sym b
print sa
print $ chol sa
print sb
print $ chol sb
print $ tr $ chol sb
 
</syntaxhighlight>
{{out}}
<pre>Herm (3><3)
[ 25.0, 15.0, -5.0
, 15.0, 18.0, 0.0
, -5.0, 0.0, 11.0 ]
(3><3)
[ 5.0, 3.0, -1.0
, 0.0, 3.0, 1.0
, 0.0, 0.0, 3.0 ]
Herm (4><4)
[ 18.0, 22.0, 54.0, 42.0
, 22.0, 70.0, 86.0, 62.0
, 54.0, 86.0, 174.0, 134.0
, 42.0, 62.0, 134.0, 106.0 ]
(4><4)
[ 4.242640687119285, 5.185449728701349, 12.727922061357857, 9.899494936611665
, 0.0, 6.565905201197403, 3.0460384954008553, 1.6245538642137891
, 0.0, 0.0, 1.6497422479090704, 1.849711005231382
, 0.0, 0.0, 0.0, 1.3926212476455904 ]
(4><4)
[ 4.242640687119285, 0.0, 0.0, 0.0
, 5.185449728701349, 6.565905201197403, 0.0, 0.0
, 12.727922061357857, 3.0460384954008553, 1.6497422479090704, 0.0
, 9.899494936611665, 1.6245538642137891, 1.849711005231382, 1.3926212476455904 ]</pre>
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure cholesky (array)
result := make_square_array (*array)
every (i := 1 to *array) do {
Line 1,394 ⟶ 2,225:
do_cholesky ([[25,15,-5],[15,18,0],[-5,0,11]])
do_cholesky ([[18,22,54,42],[22,70,86,62],[54,86,174,134],[42,62,134,106]])
end</langsyntaxhighlight>
{{out}}
<pre>
Line 1,416 ⟶ 2,247:
9.899494937 1.624553864 1.849711005 1.392621248
</pre>
 
=={{header|Idris}}==
'''works with Idris 0.10'''
 
'''Solution:'''
<langsyntaxhighlight Idrislang="idris">module Main
 
import Data.Vect
Line 1,488 ⟶ 2,318:
print ex2
putStrLn "\n"
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,496 ⟶ 2,326:
[[4.242640687119285, 0, 0, 0], [5.185449728701349, 6.565905201197403, 0, 0], [12.72792206135786, 3.046038495400855, 1.64974224790907, 0], [9.899494936611665, 1.624553864213789, 1.849711005231382, 1.392621247645587]]
</pre>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">mp=: +/ . * NB. matrix product
h =: +@|: NB. conjugate transpose
 
Line 1,513 ⟶ 2,342:
L0,(T mp L0),.L1
end.
)</langsyntaxhighlight>
See [[j:Essays/Cholesky Decomposition|Cholesky Decomposition essay]] on the J Wiki.
{{out|Examples}}
<langsyntaxhighlight lang="j"> eg1=: 25 15 _5 , 15 18 0 ,: _5 0 11
eg2=: 18 22 54 42 , 22 70 86 62 , 54 86 174 134 ,: 42 62 134 106
cholesky eg1
Line 1,526 ⟶ 2,355:
5.18545 6.56591 0 0
12.7279 3.04604 1.64974 0
9.89949 1.62455 1.84971 1.39262</langsyntaxhighlight>
'''Using `math/lapack` addon'''
<langsyntaxhighlight lang="j"> load 'math/lapack'
load 'math/lapack/potrf'
potrf_jlapack_ eg1
Line 1,538 ⟶ 2,367:
5.18545 6.56591 0 0
12.7279 3.04604 1.64974 0
9.89949 1.62455 1.84971 1.39262</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class Cholesky {
Line 1,572 ⟶ 2,400:
System.out.println(Arrays.deepToString(chol(test2)));
}
}</langsyntaxhighlight>
{{out}}
<pre>[[5.0, 0.0, 0.0], [3.0, 3.0, 0.0], [-1.0, 1.0, 3.0]]
[[4.242640687119285, 0.0, 0.0, 0.0], [5.185449728701349, 6.565905201197403, 0.0, 0.0], [12.727922061357857, 3.0460384954008553, 1.6497422479090704, 0.0], [9.899494936611667, 1.624553864213788, 1.8497110052313648, 1.3926212476456026]]</pre>
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
const cholesky = function (array) {
const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0));
const L = zeros.map((row, r, xL) => row.map((v, c) => {
const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0);
return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - sum) : (array[r][c] - sum) / xL[c][c] : v;
}));
return L;
}
 
let arr3 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]];
console.log(cholesky(arr3));
let arr4 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]];
console.log(cholesky(arr4));
</syntaxhighlight>
 
{{output}}
<pre>
0: (3) [5, 0, 0]
1: (3) [3, 3, 0]
2: (3) [-1, 1, 3]
 
0: (4) [4.242640687119285, 0, 0, 0]
1: (4) [5.185449728701349, 6.565905201197403, 0, 0]
2: (4) [12.727922061357857, 3.0460384954008553, 1.6497422479090704, 0]
3: (4) [9.899494936611665, 1.6245538642137891, 1.849711005231382, 1.3926212476455924]
</pre>
=={{header|jq}}==
{{Works with|jq|1.4}}
'''Infrastructure''':
<langsyntaxhighlight lang="jq"># Create an m x n matrix
def matrix(m; n; init):
if m == 0 then []
Line 1,618 ⟶ 2,473:
else [ ., 0, 0, length ] | test
end ;
</langsyntaxhighlight>'''Cholesky Decomposition''':<syntaxhighlight lang ="jq">def cholesky_factor:
if is_symmetric then
length as $length
Line 1,639 ⟶ 2,494:
end ))
else error( "cholesky_factor: matrix is not symmetric" )
end ;</langsyntaxhighlight>
'''Task 1''':
[[25,15,-5],[15,18,0],[-5,0,11]] | cholesky_factor
Line 1,650 ⟶ 2,505:
[42, 62, 134, 106]] | cholesky_factor | neatly(20)
{{Out}}
<langsyntaxhighlight lang="jq"> 4.242640687119285 0 0 0
5.185449728701349 6.565905201197403 0 0
12.727922061357857 3.0460384954008553 1.6497422479090704 0
9.899494936611665 1.6245538642137891 1.849711005231382 1.3926212476455924</langsyntaxhighlight>
 
=={{header|Julia}}==
Julia's strong linear algebra support includes Cholesky decomposition.
<syntaxhighlight lang="julia">
<lang Julia>
a = [25 15 5; 15 18 0; -5 0 11]
b = [18 22 54 22; 22 70 86 62; 54 86 174 134; 42 62 134 106]
Line 1,663 ⟶ 2,517:
println(a, "\n => \n", chol(a, :L))
println(b, "\n => \n", chol(b, :L))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,684 ⟶ 2,538:
9.899494936611667 1.624553864213788 1.8497110052313648 1.3926212476456026]
</pre>
 
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun cholesky(a: DoubleArray): DoubleArray {
Line 1,726 ⟶ 2,579:
val c2 = cholesky(m2)
showMatrix(c2)
}</langsyntaxhighlight>
 
{{out}}
Line 1,739 ⟶ 2,592:
9.89949 1.62455 1.84971 1.39262
</pre>
=={{header|Lobster}}==
{{trans|Go}}
Translated from the Go Real version: This version works with real matrices, like most other solutions on the page. The representation is packed, however, storing only the lower triange of the input symetric matrix and the output lower matrix. The decomposition algorithm computes rows in order from top to bottom but is a little different than Cholesky–Banachiewicz.
<syntaxhighlight lang="lobster">import std
 
// choleskyLower returns the cholesky decomposition of a symmetric real
// matrix. The matrix must be positive definite but this is not checked
def choleskyLower(order, a) -> [float]:
let l = map(a.length): 0.0
var row, col = 1, 1
var dr = 0 // index of diagonal element at end of row
var dc = 0 // index of diagonal element at top of column
for(a) e, i:
if i < dr:
let d = (e - l[i]) / l[dc]
l[i] = d
var ci, cx = col, dc
var j = i + 1
while j <= dr:
cx += ci
ci += 1
l[j] += d * l[cx]
j += 1
col += 1
dc += col
else:
l[i] = sqrt(e - l[i])
row += 1
dr += row
col = 1
dc = 0
return l
 
// symmetric.print prints a square matrix from the packed representation,
// printing the upper triange as a transpose of the lower
def print_symmetric(order, s):
//const eleFmt = "%10.5f "
var str = ""
var row, diag = 1, 0
for(s) e, i:
str += e + " " // format?
if i == diag:
var j, col = diag+row, row
while col < order:
str += s[j] + " " // format?
col++
j += col
print(str); str = ""
row += 1
diag += row
 
// lower.print prints a square matrix from the packed representation,
// printing the upper triangle as all zeros.
def print_lower(order, l):
//const eleFmt = "%10.5f "
var str = ""
var row, diag = 1, 0
for(l) e, i:
str += e + " " // format?
if i == diag:
var j = row
while j < order:
str += 0.0 + " " // format?
j += 1
print(str); str = ""
row += 1
diag += row
 
def demo(order, a):
print("A:")
print_symmetric(order, a)
print("L:")
print_lower(order, choleskyLower(order, a))
 
demo(3, [25.0,
15.0, 18.0,
-5.0, 0.0, 11.0])
 
demo(4, [18.0,
22.0, 70.0,
54.0, 86.0, 174.0,
42.0, 62.0, 134.0, 106.0])
</syntaxhighlight>
{{out}}
<pre>
A:
25.0 15.0 -5.0
15.0 18.0 0.0
-5.0 0.0 11.0
L:
5.0 0.0 0.0
3.0 3.0 0.0
-1.0 1.0 3.0
A:
18.0 22.0 54.0 42.0
22.0 70.0 86.0 62.0
54.0 86.0 174.0 134.0
42.0 62.0 134.0 106.0
L:
4.242640687119 0.0 0.0 0.0
5.185449728701 6.565905201197 0.0 0.0
12.72792206135 3.046038495401 1.649742247909 0.0
9.899494936612 1.624553864214 1.849711005231 1.392621247646
</pre>
=={{header|Maple}}==
The Cholesky decomposition is obtained by passing the `method = Cholesky' option to the LUDecomposition procedure in the LinearAlgebra pacakge. This is illustrated below for the two requested examples. The first is computed exactly; the second is also, but the subsequent application of `evalf' to the result produces a matrix with floating point entries which can be compared with the expected output in the problem statement.
<langsyntaxhighlight Maplelang="maple">> A := << 25, 15, -5; 15, 18, 0; -5, 0, 11 >>;
[25 15 -5]
[ ]
Line 1,793 ⟶ 2,749:
[12.72792206 3.046038495 1.649742248 0. ]
[ ]
[9.899494934 1.624553864 1.849711006 1.392621248]</langsyntaxhighlight>
 
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]</langsyntaxhighlight>
Without the use of built-in functions, making use of memoization:
<langsyntaxhighlight Mathematicalang="mathematica">chol[A_] :=
Module[{L},
L[k_, k_] := L[k, k] = Sqrt[A[[k, k]] - Sum[L[k, j]^2, {j, 1, k-1}]];
L[i_, k_] := L[i, k] = L[k, k]^-1 (A[[i, k]] - Sum[L[i, j] L[k, j], {j, 1, k-1}]);
PadRight[Table[L[i, j], {i, Length[A]}, {j, i}]]
]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
The cholesky decomposition chol() is an internal function
<langsyntaxhighlight Matlablang="matlab"> A = [
25 15 -5
15 18 0
Line 1,821 ⟶ 2,774:
[L] = chol(A,'lower')
[L] = chol(B,'lower')
</syntaxhighlight>
</lang>
{{out}}
<pre> > [L] = chol(A,'lower')
Line 1,837 ⟶ 2,790:
9.89949 1.62455 1.84971 1.39262
</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Cholesky decomposition is built-in */
 
a: hilbert_matrix(4)$
Line 1,850 ⟶ 2,802:
b . transpose(b) - a;
matrix([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0])</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import math, strutils, strformat
 
type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]
 
proc cholesky[TMatrix](a: TMatrix): TMatrix =
for i in 0 .. < a[0].len:
for j in 0 .. i:
var s = 0.0
for k in 0 .. < j:
s += result[i][k] * result[j][k]
result[i][j] = if i == j: sqrt(a[i][i]-s)
else: (1.0 / result[j][j] * (a[i][j] - s))
 
proc `$`(a: Matrix): string =
result = ""
for b in a:
var line = ""
for c in b:
line.addSep(" ", 0)
result.add c.formatFloat(ffDecimal, 5) & " "
result line.add fmt"\n{c:8.5f}"
result.add line & '\n'
 
let m1 = [[25.0, 15.0, -5.0],
Line 1,881 ⟶ 2,836:
[54.0, 86.0, 174.0, 134.0],
[42.0, 62.0, 134.0, 106.0]]
echo cholesky(m2)</langsyntaxhighlight>
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
<pre> 5.1854500000 6.56591 0.00000 0.00000
12 3.7279200000 3.0460400000 1.64974 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}}==
{{trans|C}}
 
<langsyntaxhighlight lang="objeck">
class Cholesky {
function : Main(args : String[]) ~ Nil {
Line 1,939 ⟶ 2,894:
}
}
</syntaxhighlight>
</lang>
 
<pre>
Line 1,951 ⟶ 2,906:
9.89949494 1.62455386 1.84971101 1.39262125
</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight OCamllang="ocaml">let cholesky inp =
let n = Array.length inp in
let res = Array.make_matrix n n 0.0 in
Line 1,982 ⟶ 2,936:
[|22.0; 70.0; 86.0; 62.0|];
[|54.0; 86.0; 174.0; 134.0|];
[|42.0; 62.0; 134.0; 106.0|] |];</langsyntaxhighlight>
{{out}}
<pre>in:
Line 2,003 ⟶ 2,957:
12.72792 3.04604 1.64974 0.00000
9.89949 1.62455 1.84971 1.39262</pre>
 
=={{header|ooRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="oorexx">/*REXX program performs the Cholesky decomposition on a square matrix. */
niner = '25 15 -5' , /*define a 3x3 matrix. */
'15 18 0' ,
Line 2,056 ⟶ 3,009:
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return (g/1)i /*make complex if X < 0.*/</langsyntaxhighlight>
 
 
 
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">cholesky(M) =
{
my (L = matrix(#M,#M));
Line 2,073 ⟶ 3,023:
);
L
}</langsyntaxhighlight>
 
Output: (set displayed digits with: \p 5)
Line 2,095 ⟶ 3,045:
[9.8995 1.6246 1.8497 1.3926]
</pre>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Programprogram CholeskyCholeskyApp;
 
type
D2Array = array of array of double;
 
function cholesky(const A: D2Array): D2Array;
var
i, j, k: integer;
s: double;
begin
setlength(choleskyResult, length(A), length(A));
for i := low(choleskyResult) to high(choleskyResult) do
for j := 0 to i do
begin
s := 0;
for k := 0 to j - 1 do
s := s + choleskyResult[i][k] * choleskyResult[j][k];
if i = j then
cholesky Result[i][j] := sqrt(A[i][i] - s)
else
choleskyResult[i][j] := (A[i][j] - s) / choleskyResult[j][j]; // save one multiplication compared to the original
end;
end;
 
procedure printM(const A: D2Array);
var
i, j: integer;
begin
for i := low(A) to high(A) do
begin
for ij := low(A) to high(A) do
write(A[i, j]: 8: 5);
begin
writeln;
for j := low(A) to high(A) do
write(A[i,j]:8:5);
writeln;
end;
end;
end;
 
const
m1: array[0..2, 0..2] of double = ((25, 15, -5), (15, 18, 0), (-5, 0, 11));
m2: array[0..3, 0..3] of double = ((18, 22, 54, 42), (22, 70, 86, 62), (54, 86,
(15, 18, 0),
174, 134), (-542, 62, 0134, 11106));
 
m2: array[0..3,0..3] of double = ((18, 22, 54, 42),
(22, 70, 86, 62),
(54, 86, 174, 134),
(42, 62, 134, 106));
var
index, i: integer;
cIn, cOut: D2Array;
 
Line 2,148 ⟶ 3,094:
setlength(cIn, length(m1), length(m1));
for index := low(m1) to high(m1) do
begin
cIn[index] := m1[index];
SetLength(cIn[index], length(m1[index]));
for i := 0 to High(m1[Index]) do
cIn[index][i] := m1[index][i];
end;
cOut := cholesky(cIn);
printM(cOut);
 
writeln;
 
setlength(cIn, length(m2), length(m2));
for index := low(m2) to high(m2) do
begin
cIn[index] := m2[index];
SetLength(cIn[index], length(m2[Index]));
for i := 0 to High(m2[Index]) do
cIn[index][i] := m2[index][i];
end;
cOut := cholesky(cIn);
printM(cOut);
end.</syntaxhighlight>
 
end.</lang>
{{out}}
<pre>
Line 2,172 ⟶ 3,125:
9.89949 1.62455 1.84971 1.39262
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub cholesky {
my $matrix = shift;
my $chol = [ map { [(0) x @$matrix ] } @$matrix ];
Line 2,199 ⟶ 3,151:
print "\nExample 2:\n";
print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,213 ⟶ 3,165:
9.8995 1.6246 1.8497 1.3926
</pre>
=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
<lang perl6>sub cholesky(@A) {
my @L = @A »*» 0;
for ^@A -> $i {
for 0..$i -> $j {
@L[$i][$j] = ($i == $j ?? &sqrt !! 1/@L[$j][$j] * * )(
@A[$i][$j] - [+] (@L[$i;*] Z* @L[$j;*])[^$j]
);
}
}
return @L;
}
.say for cholesky [
[25],
[15, 18],
[-5, 0, 11],
];
 
.say for cholesky [
[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106],
];</lang>
 
=={{header|Phix}}==
{{trans|Sidef}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function cholesky(sequence matrix)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer l = length(matrix)
<span style="color: #008080;">function</span> <span style="color: #000000;">cholesky</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">matrix</span><span style="color: #0000FF;">)</span>
sequence chol = repeat(repeat(0,l),l)
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">matrix</span><span style="color: #0000FF;">)</span>
for row=1 to l do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">chol</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">),</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)</span>
for col=1 to row do
<span style="color: #008080;">for</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
atom x = matrix[row][col]
<span style="color: #008080;">for</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">row</span> <span style="color: #008080;">do</span>
for i=1 to col do
<span style="color: #004080;">atom</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">matrix</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">][</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span>
x -= chol[row][i] * chol[col][i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">col</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">x</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">chol</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">][</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">chol</span><span style="color: #0000FF;">[</span><span style="color: #000000;">col</span><span style="color: #0000FF;">][</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
chol[row][col] = iff(row == col ? sqrt(x) : x/chol[col][col])
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #000000;">chol</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">][</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">row</span> <span style="color: #0000FF;">==</span> <span style="color: #000000;">col</span> <span style="color: #0000FF;">?</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">:</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">/</span><span style="color: #000000;">chol</span><span style="color: #0000FF;">[</span><span style="color: #000000;">col</span><span style="color: #0000FF;">][</span><span style="color: #000000;">col</span><span style="color: #0000FF;">])</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return chol
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">chol</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
ppOpt({pp_Nest,1})
pp(cholesky({{ 25, 15, -5 },
<span style="color: #7060A8;">ppOpt</span><span style="color: #0000FF;">({</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
{ 15, 18, 0 },
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cholesky</span><span style="color: #0000FF;">({{</span> <span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">5</span> <span style="color: #0000FF;">},</span>
{ -5, 0, 11 }}))
<span style="color: #0000FF;">{</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">18</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span> <span style="color: #0000FF;">},</span>
pp(cholesky({{ 18, 22, 54, 42},
<span style="color: #0000FF;">{</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">11</span> <span style="color: #0000FF;">}}))</span>
{ 22, 70, 86, 62},
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cholesky</span><span style="color: #0000FF;">({{</span> <span style="color: #000000;">18</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">22</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">54</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">42</span><span style="color: #0000FF;">},</span>
{ 54, 86, 174, 134},
<span style="color: #0000FF;">{</span> <span style="color: #000000;">22</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">70</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">86</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">62</span><span style="color: #0000FF;">},</span>
{ 42, 62, 134, 106}}))</lang>
<span style="color: #0000FF;">{</span> <span style="color: #000000;">54</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">86</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">174</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">134</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span> <span style="color: #000000;">42</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">62</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">134</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">106</span><span style="color: #0000FF;">}}))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,274 ⟶ 3,203:
{9.899494937,1.624553864,1.849711005,1.392621248}}
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 9)
(load "@lib/math.l")
 
Line 2,292 ⟶ 3,220:
(for R L
(for N R (prin (align 9 (round N 5))))
(prinl) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(cholesky
'((25.0 15.0 -5.0) (15.0 18.0 0) (-5.0 0 11.0)) )
 
Line 2,304 ⟶ 3,232:
(22.0 70.0 86.0 62.0)
(54.0 86.0 174.0 134.0)
(42.0 62.0 134.0 106.0) ) )</langsyntaxhighlight>
{{out}}
<pre> 5.00000 0.00000 0.00000
Line 2,314 ⟶ 3,242:
12.72792 3.04604 1.64974 0.00000
9.89949 1.62455 1.84971 1.39262</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(subscriptrange):
decompose: procedure options (main); /* 31 October 2013 */
declare a(*,*) float controlled;
Line 2,362 ⟶ 3,289:
end cholesky;
 
end decompose;</langsyntaxhighlight>
ACTUAL RESULTS:-
<pre>Original matrix:
Line 2,383 ⟶ 3,310:
9.89950 1.62455 1.84971 1.39262
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function cholesky ($a) {
$l = @()
Line 2,391 ⟶ 3,317:
$n = $a.count
$end = $n - 1
$l = 1..$n | foreach {$row = @(0) * $n; ,$row}
foreach ($i in 0..$end) {$l[$i] = @(0) * $n}
foreach ($k in 0..$end) {
$m = $k - 1
Line 2,413 ⟶ 3,338:
$l
}
 
function show($a) {$a | foreach {"$_"}}
if($a) {
0..($a.Count - 1) | foreach{ if($a[$_]){"$($a[$_])"}else{""} }
}
}
 
$a1 = @(
@(25, 15, -5),
Line 2,442 ⟶ 3,363:
"l2 ="
show (cholesky $a2)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,467 ⟶ 3,388:
9.89949493661167 1.62455386421379 1.84971100523138 1.39262124764559
</pre>
 
=={{header|Python}}==
===Python2.X version===
<langsyntaxhighlight lang="python">from __future__ import print_function
 
from pprint import pprint
Line 2,496 ⟶ 3,416:
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)</langsyntaxhighlight>
 
{{out}}
Line 2,510 ⟶ 3,430:
Factors out accesses to <code>A[i], L[i], and L[j]</code> by creating <code>Ai, Li and Lj</code> respectively as well as using <code>enumerate</code> instead of <code>range(len(some_array))</code>.
 
<langsyntaxhighlight lang="python">def cholesky(A):
L = [[0.0] * len(A) for _ in range(len(A))]
for i, (Ai, Li) in enumerate(zip(A, L)):
Line 2,517 ⟶ 3,437:
Li[j] = sqrt(Ai[i] - s) if (i == j) else \
(1.0 / Lj[j] * (Ai[j] - s))
return L</langsyntaxhighlight>
 
{{out}}
(As above)
 
=={{header|q}}==
 
<langsyntaxhighlight lang="q">solve:{[A;B] $[0h>type A;B%A;inv[A] mmu B]}
ak:{[m;k] (),/:m[;k]til k:k-1}
akk:{[m;k] m[k;k:k-1]}
Line 2,539 ⟶ 3,458:
show cholesky (25 15 -5f;15 18 0f;-5 0 11f)
-1"";
show cholesky (18 22 54 42f;22 70 86 62f;54 86 174 134f;42 62 134 106f)</langsyntaxhighlight>
 
{{out}}
Line 2,551 ⟶ 3,470:
9.899495 1.624554 1.849711 1.392621
</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3)))
# [,1] [,2] [,3]
# [1,] 5 0 0
Line 2,564 ⟶ 3,482:
# [2,] 5.185450 6.565905 0.000000 0.000000
# [3,] 12.727922 3.046038 1.649742 0.000000
# [4,] 9.899495 1.624554 1.849711 1.392621</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,596 ⟶ 3,513:
[54 86 174 134]
[42 62 134 106]]))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
'#(#(5 0 0)
#(3 3 0)
Line 2,607 ⟶ 3,524:
#( 9.899494936611665 1.6245538642137891 1.849711005231382 1.3926212476455924))
 
</syntaxhighlight>
</lang>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub cholesky(@A) {
my @L = @A »×» 0;
for ^@A -> \i {
for 0..i -> \j {
@L[i;j] = (i == j ?? &sqrt !! 1/@L[j;j] × * )\ # select function
(@A[i;j] - [+] (@L[i;*] Z× @L[j;*])[^j]) # provide value
}
}
@L
}
 
.fmt('%3d').say for cholesky [
[25],
[15, 18],
[-5, 0, 11],
];
 
say '';
 
.fmt('%6.3f').say for cholesky [
[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106],
];</syntaxhighlight>
{{out}}
<pre> 5
3 3
-1 1 3
 
4.243 0.000 0.000 0.000
5.185 6.566 0.000 0.000
12.728 3.046 1.650 0.000
9.899 1.625 1.850 1.393</pre>
=={{header|REXX}}==
If trailing zeros are wanted after the decimal point for values of zero (0), &nbsp; the &nbsp; &nbsp; <big><big>'''/ 1'''</big></big> &nbsp; &nbsp; (a division by unity performs
<br>REXX number normalization) &nbsp; can be removed from the line &nbsp; (number 40) &nbsp; which contains the source statement:
::::: &nbsp; <b> z=z &nbsp; right( format(@.row.col, , &nbsp; dPlaces) / 1, &nbsp; &nbsp; width) </b>
<langsyntaxhighlight lang="rexx">/*REXX program performs the Cholesky decomposition on a square matrix & displays results*/
niner = '25 15 -5' , /*define a 3x3 matrix with elements. */
'15 18 0' ,
Line 2,628 ⟶ 3,580:
do r=1 for ord
do c=1 for r; $=0; do i=1 for c-1; $= $ + !.r.i * !.c.i; end /*i*/
if r=c then !.r.r= sqrt(!.r.r - $) / 1
else !.r.c= 1 / !.c.c * (@.r.c - $)
end /*c*/
Line 2,661 ⟶ 3,613:
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ %2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g/1</langsyntaxhighlight>
{{out|output}}
<pre>
Line 2,692 ⟶ 3,644:
9.89949 1.62455 1.84971 1.39262
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Cholesky decomposition
# Date : 2017/11/12
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
 
load "stdlib.ring"
Line 2,740 ⟶ 3,688:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,752 ⟶ 3,700:
9.89949 1.62455 1.84971 1.39262
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'matrix'
 
class Matrix
def symmetric?
return false if not square?
(0 ... row_size).each do |i|
(0 .. i).each do |j|
return false if self[i,j] != self[j,i]
end
end
true
end
 
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
Line 2,791 ⟶ 3,728:
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor</langsyntaxhighlight>
{{out}}
<pre>
Line 2,804 ⟶ 3,741:
 
{{trans|C}}
<langsyntaxhighlight lang="rust">fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
Line 2,844 ⟶ 3,781:
show_matrix(res2, dimension);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,857 ⟶ 3,794:
9.8995 1.6246 1.8497 1.3926
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">case class Matrix( val matrix:Array[Array[Double]] ) {
 
// Assuming matrix is positive-definite, symmetric and not empty...
Line 2,919 ⟶ 3,855:
(l2.matrix.flatten.zip(r2)).foreach{ case (result,test) =>
assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)
}</langsyntaxhighlight>
 
=={{header|Scilab}}==
 
The Cholesky decomposition is builtin, and an upper triangular matrix is returned, such that $A=L^TL$.
 
<langsyntaxhighlight lang="scilab">a = [25 15 -5; 15 18 0; -5 0 11];
chol(a)
ans =
Line 2,943 ⟶ 3,878:
0. 6.5659052 3.0460385 1.6245539
0. 0. 1.6497422 1.849711
0. 0. 0. 1.3926212</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
Line 3,005 ⟶ 3,939:
writeln;
writeMat(cholesky(m2));
end func;</langsyntaxhighlight>
 
Output:
Line 3,018 ⟶ 3,952:
9.89950 1.62455 1.84971 1.39262
</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func cholesky(matrix) {
var chol = matrix.len.of { matrix.len.of(0) }
for row in ^matrix {
Line 3,033 ⟶ 3,966:
}
return chol
}</langsyntaxhighlight>
 
Examples:
<langsyntaxhighlight lang="ruby">var example1 = [ [ 25, 15, -5 ],
[ 15, 18, 0 ],
[ -5, 0, 11 ] ];
Line 3,053 ⟶ 3,986:
cholesky(example2).each { |row|
say row.map {'%7.4f' % _}.join(' ');
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,067 ⟶ 4,000:
9.8995 1.6246 1.8497 1.3926
</pre>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">
<lang Smalltalk>
FloatMatrix>>#cholesky
| l |
Line 3,092 ⟶ 4,024:
l at: k @ i put: aki - partialSum * factor reciprocal]]].
^l
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
See [http://www.stata.com/help.cgi?mf_cholesky Cholesky square-root decomposition] in Stata help.
<langsyntaxhighlight lang="stata">mata
: a=25,15,-5\15,18,0\-5,0,11
 
Line 3,135 ⟶ 4,066:
3 | 12.72792206 3.046038495 1.649742248 0 |
4 | 9.899494937 1.624553864 1.849711005 1.392621248 |
+---------------------------------------------------------+</langsyntaxhighlight>
=={{header|Swift}}==
{{trans|Rust}}
 
<syntaxhighlight lang="swift">func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
 
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
 
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
 
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
 
return res
}
 
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
 
print()
}
}
 
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
 
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
 
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)</syntaxhighlight>
 
{{out}}
<pre>5.0 0.0 0.0
3.0 3.0 0.0
-1.0 1.0 3.0
 
4.242640687119285 0.0 0.0 0.0
5.185449728701349 6.565905201197403 0.0 0.0
12.727922061357857 3.0460384954008553 1.6497422479090704 0.0
9.899494936611667 1.624553864213788 1.8497110052313648 1.3926212476456026</pre>
=={{header|Tcl}}==
{{trans|Java}}
<langsyntaxhighlight lang="tcl">proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
Line 3,157 ⟶ 4,150:
}
return $l
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">set test1 {
{25 15 -5}
{15 18 0}
Line 3,171 ⟶ 4,164:
{42 62 134 106}
}
puts [cholesky $test2]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,177 ⟶ 4,170:
{4.242640687119285 0.0 0.0 0.0} {5.185449728701349 6.565905201197403 0.0 0.0} {12.727922061357857 3.0460384954008553 1.6497422479090704 0.0} {9.899494936611667 1.624553864213788 1.8497110052313648 1.3926212476456026}
</pre>
 
=={{header|VBA}}==
This function returns the lower Cholesky decomposition of a square matrix fed to it. It does not check for positive semi-definiteness, although it does check for squareness. It assumes that <code>Option Base 0</code> is set, and thus the matrix entry indices need to be adjusted if Base is set to 1. It also assumes a matrix of size less than 256x256. To handle larger matrices, change all <code>Byte</code>-type variables to <code>Long</code>. It takes the square matrix range as an input, and can be implemented as an array function on the same sized square range of cells as output. For example, if the matrix is in cells A1:E5, highlighting cells A10:E14, typing "<code>=Cholesky(A1:E5)</code>" and htting <code>Ctrl-Shift-Enter</code> will populate the target cells with the lower Cholesky decomposition.
 
<langsyntaxhighlight lang="vb">Function Cholesky(Mat As Range) As Variant
 
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Line 3,233 ⟶ 4,225:
Cholesky = L
End Function
</syntaxhighlight>
</lang>
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">import math
 
// Symmetric and Lower use a packed representation that stores only
// the Lower triangle.
struct Symmetric {
order int
ele []f64
}
struct Lower {
mut:
order int
ele []f64
}
// Symmetric.print prints a square matrix from the packed representation,
// printing the upper triange as a transpose of the Lower.
fn (s Symmetric) print() {
mut row, mut diag := 1, 0
for i, e in s.ele {
print("${e:10.5f} ")
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
print("${s.ele[j]:10.5f} ")
col++
}
println('')
row++
diag += row
}
}
}
// Lower.print prints a square matrix from the packed representation,
// printing the upper triangle as all zeros.
fn (l Lower) print() {
mut row, mut diag := 1, 0
for i, e in l.ele {
print("${e:10.5f} ")
if i == diag {
for _ in row..l.order {
print("${0.0:10.5f} ")
}
println('')
row++
diag += row
}
}
}
// cholesky_lower returns the cholesky decomposition of a Symmetric real
// matrix. The matrix must be positive definite but this is not checked.
fn (a Symmetric) cholesky_lower() Lower {
mut l := Lower{a.order, []f64{len: a.ele.len}}
mut row, mut col := 1, 1
mut dr := 0 // index of diagonal element at end of row
mut dc := 0 // index of diagonal element at top of column
for i, e in a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
mut ci, mut cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
fn main() {
demo(Symmetric{3, [
f64(25),
15, 18,
-5, 0, 11]})
demo(Symmetric{4, [
f64(18),
22, 70,
54, 86, 174,
42, 62, 134, 106]})
}
fn demo(a Symmetric) {
println("A:")
a.print()
println("L:")
a.cholesky_lower().print()
}</syntaxhighlight>
 
{{out}}
<pre>
A:
25.00000 15.00000 -5.00000
15.00000 18.00000 0.00000
-5.00000 0.00000 11.00000
L:
5.00000 0.00000 0.00000
3.00000 3.00000 0.00000
-1.00000 1.00000 3.00000
A:
18.00000 22.00000 54.00000 42.00000
22.00000 70.00000 86.00000 62.00000
54.00000 86.00000 174.00000 134.00000
42.00000 62.00000 134.00000 106.00000
L:
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.3926
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var arrays = [
[ [25, 15, -5],
[15, 18, 0],
[-5, 0, 11] ],
 
[ [18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106] ]
]
 
for (array in arrays) {
System.print("Original:")
Fmt.mprint(array, 3, 0)
System.print("\nLower Cholesky factor:")
Fmt.mprint(Matrix.new(array).cholesky(), 8, 5)
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Original:
| 25 15 -5|
| 15 18 0|
| -5 0 11|
 
Lower Cholesky factor:
| 5.00000 0.00000 0.00000|
| 3.00000 3.00000 0.00000|
|-1.00000 1.00000 3.00000|
 
Original:
| 18 22 54 42|
| 22 70 86 62|
| 54 86 174 134|
| 42 62 134 106|
 
Lower Cholesky factor:
| 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|XPL0}}==
<syntaxhighlight lang "XPL0">real L(4*4);
 
func real Cholesky(A, N);
real A; int N;
real S;
int I, J, K;
[for I:= 0 to N*N-1 do L(I):= 0.;
for I:= 0 to N-1 do
for J:= 0 to I do
[S:= 0.;
for K:= 0 to J-1 do
S:= S + L(I*N+K) * L(J*N+K);
L(I*N+J):= if I = J then sqrt(A(I*N+I) - S)
else (1.0 / L(J*N+J) * (A(I*N+J) - S));
];
return L;
];
 
proc ShowMatrix(A, N);
real A; int N;
int I, J;
[for I:= 0 to N-1 do
[for J:= 0 to N-1 do
RlOut(0, A(I*N+J));
CrLf(0);
];
];
 
int N;
real M1, C1, M2, C2;
[N:= 3;
M1:= [25., 15., -5.,
15., 18., 0.,
-5., 0., 11.];
C1:= Cholesky(M1, N);
ShowMatrix(C1, N);
CrLf(0);
 
N:= 4;
M2:= [18., 22., 54., 42.,
22., 70., 86., 62.,
54., 86., 174., 134.,
42., 62., 134., 106.];
C2:= Cholesky(M2, N);
ShowMatrix(C2, N);
]</syntaxhighlight>
{{out}}
<pre>
5.00000 0.00000 0.00000
3.00000 3.00000 0.00000
-1.00000 1.00000 3.00000
 
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|zkl}}==
Using the GNU Scientific Library:
<langsyntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn lowerCholesky(m){ // trans: C
rows:=m.rows;
Line 3,247 ⟶ 4,471:
}
lcm
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,273 ⟶ 4,497:
Or, using lists:
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn cholesky(mat){
rows:=mat.len();
r:=(0).pump(rows,List().write, (0).pump(rows,List,0.0).copy); // matrix of zeros
Line 3,282 ⟶ 4,506:
}
r
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">ex1:=L( L(25.0,15.0,-5.0), L(15.0,18.0,0.0), L(-5.0,0.0,11.0) );
printM(cholesky(ex1));
println("-----------------");
Line 3,290 ⟶ 4,514:
L(54.0, 86.0, 174.0, 134.0,),
L(42.0, 62.0, 134.0, 106.0,) );
printM(cholesky(ex2));</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%9.5f "*row.len()).fmt(row.xplode()) }</langsyntaxhighlight>
{{out}}
<pre>
Line 3,304 ⟶ 4,528:
9.89949 1.62455 1.84971 1.39262
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET d=2000: GO SUB 1000: GO SUB 4000: GO SUB 5000
20 LET d=3000: GO SUB 1000: GO SUB 4000: GO SUB 5000
30 STOP
Line 3,341 ⟶ 4,564:
5050 PRINT
5060 NEXT r
5070 RETURN</langsyntaxhighlight>
9,476

edits