Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided Fortran code into VB while preserving the original functionality.
Program Cholesky_decomp implicit none INTEGER, PARAMETER :: m=3 INTEGER, PARAMETER :: n=3 COMPLEX, DIMENSION(m,n) :: A REAL, DIMENSION(m,n) :: L REAL :: sum1, sum2 INTEGER i,j,k A(1,:)=(/ 25, 15, -5 /) A(2,:)=(/ 15, 18, 0 /) A(3,:)=(/ -5, 0, 11 /) L(1,1)=real(sqrt(A(1,1))) L(2,1)=A(2,1)/L(1,1) L(2,2)=real(sqrt(A(2,2)-L(2,1)*L(2,1))) L(3,1)=A(3,1)/L(1,1) do i=1,n do k=1,i sum1=0 sum2=0 do j=1,k-1 if (i==k) then sum1=sum1+(L(k,j)*L(k,j)) L(k,k)=real(sqrt(A(k,k)-sum1)) elseif (i > k) then sum2=sum2+(L(i,j)*L(k,j)) L(i,k)=(1/L(k,k))*(A(i,k)-sum2) else L(i,k)=0 end if end do end do end do do i=1,m print "(3(1X,F6.1))",L(i,:) end do End program Cholesky_decomp
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Translate this program into C but keep the logic exactly as in 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 }
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Convert the following code from Groovy to C#, ensuring the logic remains intact.
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 }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Port the following code from Groovy to C++ with equivalent syntax and logic.
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 }
#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; }
Maintain the same structure and functionality when rewriting this code in Java.
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 }
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Translate this program into Python but keep the logic exactly as in 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 }
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Ensure the translated VB code behaves exactly like the original Groovy snippet.
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 }
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Write the same code in Go as shown below in 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 }
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Produce a functionally identical C code for the snippet given in Haskell.
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Convert the following code from Haskell to C++, ensuring the logic remains intact.
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
#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; }
Can you help me rewrite this code in Java instead of Haskell, keeping it the same logically?
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Translate the given Haskell code snippet into Python without altering its behavior.
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Write the same code in VB as shown below in Haskell.
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Produce a language-to-language conversion: from Haskell to Go, same semantics.
module Cholesky (Arr, cholesky) where import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST type Idx = (Int,Int) type Arr = UArray Idx Double get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]] cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Keep all operations the same but rewrite the snippet in C.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Convert the following code from Icon to C#, ensuring the logic remains intact.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Convert this Icon snippet to C++ and keep its semantics consistent.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
#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; }
Port the following code from Icon to Java with equivalent syntax and logic.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Change the following Icon code into Python without altering its purpose.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Write the same algorithm in VB as shown in this Icon implementation.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Convert this Icon block to Go, preserving its control flow and logic.
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end procedure main () 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
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Keep all operations the same but rewrite the snippet in C.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Translate this program into C# but keep the logic exactly as in J.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Please provide an equivalent version of this J code in C++.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
#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; }
Translate the given J code snippet into Java without altering its behavior.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Rewrite this program in Python while keeping its functionality equivalent to the J version.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Transform the following J implementation into VB, maintaining the same output and logic.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Convert this J block to Go, preserving its control flow and logic.
mp=: +/ . * h =: +@|: cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 end. )
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Transform the following Julia implementation into C, maintaining the same output and logic.
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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Julia version.
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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Change the programming language of this snippet from Julia to C++ without modifying what it does.
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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
#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; }
Port the provided Julia code into Java while preserving the original functionality.
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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Produce a functionally identical Python code for the snippet given in 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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Write a version of this Julia function in VB with identical behavior.
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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Can you help me rewrite this code in Go instead of Julia, keeping it the same logically?
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] println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Translate this program into C but keep the logic exactly as in Mathematica.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Please provide an equivalent version of this Mathematica code in C#.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Ensure the translated C++ code behaves exactly like the original Mathematica snippet.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
#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; }
Rewrite this program in Java while keeping its functionality equivalent to the Mathematica version.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Convert this Mathematica snippet to Python and keep its semantics consistent.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Transform the following Mathematica implementation into VB, maintaining the same output and logic.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Maintain the same structure and functionality when rewriting this code in Go.
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Convert this MATLAB snippet to C and keep its semantics consistent.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Please provide an equivalent version of this MATLAB code in C#.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Change the programming language of this snippet from MATLAB to C++ without modifying what it does.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
#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; }
Convert this MATLAB block to Java, preserving its control flow and logic.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Generate a Python translation of this MATLAB snippet without changing its computational steps.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Write the same code in VB as shown below in MATLAB.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Please provide an equivalent version of this MATLAB code in Go.
A = [ 25 15 -5 15 18 0 -5 0 11 ]; B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ]; [L] = chol(A,'lower') [L] = chol(B,'lower')
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Convert this Nim block to C, preserving its control flow and logic.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Produce a functionally identical C# code for the snippet given in Nim.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Please provide an equivalent version of this Nim code in C++.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
#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; }
Keep all operations the same but rewrite the snippet in Java.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Convert this Nim block to Python, preserving its control flow and logic.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Write the same code in VB as shown below in Nim.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Keep all operations the same but rewrite the snippet in Go.
import math, strutils, strformat type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]] proc cholesky[Matrix](a: Matrix): Matrix = 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) line.add fmt"{c:8.5f}" result.add line & '\n' let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1) let 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]] echo cholesky(m2)
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Ensure the translated C code behaves exactly like the original OCaml snippet.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Convert this OCaml snippet to C# and keep its semantics consistent.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Convert this OCaml snippet to C++ and keep its semantics consistent.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
#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; }
Write the same code in Java as shown below in OCaml.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Transform the following OCaml implementation into Python, maintaining the same output and logic.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Translate the given OCaml code snippet into VB without altering its behavior.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Write a version of this OCaml function in Go with identical behavior.
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a) let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|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|] |];
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Convert this Pascal block to C, preserving its control flow and logic.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Write a version of this Pascal function in C# with identical behavior.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Rewrite the snippet below in C++ so it works the same as the original Pascal code.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
#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; }
Please provide an equivalent version of this Pascal code in Java.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Generate an equivalent Python version of this Pascal code.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Write the same code in VB as shown below in Pascal.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Convert this Pascal block to Go, preserving its control flow and logic.
program CholeskyApp; type D2Array = array of array of double; function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; end; end; procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; 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, 174, 134), (42, 62, 134, 106)); var index, i: integer; cIn, cOut: D2Array; begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin 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 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.
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Write the same algorithm in C as shown in this Perl implementation.
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Write a version of this Perl function in C# with identical behavior.
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Change the following Perl code into C++ without altering its purpose.
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
#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; }
Convert this Perl block to Java, preserving its control flow and logic.
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Can you help me rewrite this code in Python instead of Perl, keeping it the same logically?
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Produce a language-to-language conversion: from Perl to VB, same semantics.
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Please provide an equivalent version of this Perl code in Go.
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; } my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Translate this program into C but keep the logic exactly as in PowerShell.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Rewrite the snippet below in C# so it works the same as the original PowerShell code.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Generate an equivalent C++ version of this PowerShell code.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
#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; }
Change the following PowerShell code into Java without altering its purpose.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Translate the given PowerShell code snippet into Python without altering its behavior.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Convert this PowerShell snippet to VB and keep its semantics consistent.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Transform the following PowerShell implementation into Go, maintaining the same output and logic.
function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l } function show($a) {$a | foreach {"$_"}} $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Produce a language-to-language conversion: from R to C, same semantics.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Please provide an equivalent version of this R code in C#.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Port the following code from R to C++ with equivalent syntax and logic.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
#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; }
Generate an equivalent Java version of this R code.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Convert the following code from R to Python, ensuring the logic remains intact.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Port the following code from R to VB with equivalent syntax and logic.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Port the following code from R to Go with equivalent syntax and logic.
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4)))
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Write the same code in C as shown below in Racket.
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }
Convert this Racket block to C#, preserving its control flow and logic.
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cholesky { class Program { static void Main(string[] args) { double[,] test1 = new double[,] { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11}, }; double[,] test2 = new double[,] { {18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}, }; double[,] chol1 = Cholesky(test1); double[,] chol2 = Cholesky(test2); Console.WriteLine("Test 1: "); Print(test1); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 1: "); Print(chol1); Console.WriteLine(""); Console.WriteLine("Test 2: "); Print(test2); Console.WriteLine(""); Console.WriteLine("Lower Cholesky 2: "); Print(chol2); } public static void Print(double[,] a) { int n = (int)Math.Sqrt(a.Length); StringBuilder sb = new StringBuilder(); for (int r = 0; r < n; r++) { string s = ""; for (int c = 0; c < n; c++) { s += a[r, c].ToString("f5").PadLeft(9) + ","; } sb.AppendLine(s); } Console.WriteLine(sb.ToString()); } public static double[,] Cholesky(double[,] a) { int n = (int)Math.Sqrt(a.Length); double[,] ret = new double[n, n]; for (int r = 0; r < n; r++) for (int c = 0; c <= r; c++) { if (c == r) { double sum = 0; for (int j = 0; j < c; j++) { sum += ret[c, j] * ret[c, j]; } ret[c, c] = Math.Sqrt(a[c, c] - sum); } else { double sum = 0; for (int j = 0; j < c; j++) sum += ret[r, j] * ret[c, j]; ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum); } } return ret; } } }
Can you help me rewrite this code in C++ instead of Racket, keeping it the same logically?
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
#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; }
Produce a functionally identical Java code for the snippet given in Racket.
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; } public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
Preserve the algorithm and functionality while converting the code from Racket to Python.
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print() m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
Rewrite the snippet below in VB so it works the same as the original Racket code.
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
Function Cholesky(Mat As Range) As Variant Dim A() As Double, L() As Double, sum As Double, sum2 As Double Dim m As Byte, i As Byte, j As Byte, k As Byte If Mat.Rows.Count <> Mat.Columns.Count Then MsgBox ("Correlation matrix is not square") Exit Function End If m = Mat.Rows.Count ReDim A(0 To m - 1, 0 To m - 1) ReDim L(0 To m - 1, 0 To m - 1) For i = 0 To m - 1 For j = 0 To m - 1 A(i, j) = Mat(i + 1, j + 1).Value2 L(i, j) = 0 Next j Next i Select Case m Case Is = 1 L(0, 0) = Sqr(A(0, 0)) Case Is = 2 L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) Case Else L(0, 0) = Sqr(A(0, 0)) L(1, 0) = A(1, 0) / L(0, 0) L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0)) For i = 2 To m - 1 sum2 = 0 For k = 0 To i - 1 sum = 0 For j = 0 To k sum = sum + L(i, j) * L(k, j) Next j L(i, k) = (A(i, k) - sum) / L(k, k) sum2 = sum2 + L(i, k) * L(i, k) Next k L(i, i) = Sqr(A(i, i) - sum2) Next i End Select Cholesky = L End Function
Change the following Racket code into Go without altering its purpose.
#lang racket (require math) (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L) (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]])) (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))
package main import ( "fmt" "math" ) type symmetric struct { order int ele []float64 } type lower struct { order int ele []float64 } func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } } func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } } func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 dc := 0 for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, 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 } func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) } func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
Please provide an equivalent version of this REXX code in C.
niner = '25 15 -5' , '15 18 0' , '-5 0 11' call Cholesky niner hexer = 18 22 54 42, 22 70 86 62, 54 86 174 134, 42 62 134 106 call Cholesky hexer exit Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat do r=1 for ord do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end if r=c then !.r.r=sqrt(!.r.r-d) else !.r.c=1/!.c.c*(a.r.c-d) end end call tell 'Cholesky factor',,!.,'-' return err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-' dPlaces= 5 width =10 if y=='' then !.=0 else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end w=words(x) do ord=1 until ord**2>=w; end say if ord**2\==w then call err "matrix elements don't form a square matrix." say center(hdr, ((width+1)*w)%ord, sep) say do row=1 for ord; z='' do col=1 for ord; n=n+1 a.row.col=word(x,n) if col<=row then !.row.col=a.row.col z=z right( format(a.row.col,, dPlaces) / 1, width) end say z end return sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9 numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end 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 do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end numeric digits d; return (g/1)i
#include <stdio.h> #include <stdlib.h> #include <math.h> double *cholesky(double *A, int n) { double *L = (double*)calloc(n * n, sizeof(double)); if (L == NULL) exit(EXIT_FAILURE); for (int i = 0; i < n; i++) for (int j = 0; j < (i+1); j++) { double s = 0; for (int k = 0; k < j; k++) s += L[i * n + k] * L[j * n + k]; L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s) : (1.0 / L[j * n + j] * (A[i * n + j] - s)); } return L; } void show_matrix(double *A, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%2.5f ", A[i * n + j]); printf("\n"); } } int main() { int n = 3; double m1[] = {25, 15, -5, 15, 18, 0, -5, 0, 11}; double *c1 = cholesky(m1, n); show_matrix(c1, n); printf("\n"); free(c1); n = 4; double m2[] = {18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106}; double *c2 = cholesky(m2, n); show_matrix(c2, n); free(c2); return 0; }