Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from Ada to PHP.
with Ada.Streams.Stream_IO, Ada.Directories; use Ada.Streams.Stream_IO, Ada.Directories; procedure File_Creation is File_Handle : File_Type; begin Create (File_Handle, Out_File, "output.txt"); Close (File_Handle); Create_Directory("docs"); Create (File_Handle, Out_File, "/output.txt"); Close (File_Handle); Create_Directory("/docs"); end File_Creation;
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Translate this program into PHP but keep the logic exactly as in Arturo.
output: "output.txt" docs: "docs" write output "" write.directory docs ø write join.path ["/" output] "" write.directory join.path ["/" docs] ø
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Can you help me rewrite this code in PHP instead of AutoHotKey, keeping it the same logically?
FileAppend,,output.txt FileCreateDir, docs FileAppend,,c:\output.txt FileCreateDir, c:\docs
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Maintain the same structure and functionality when rewriting this code in PHP.
BEGIN { printf "" > "output.txt" close("output.txt") printf "" > "/output.txt" close("/output.txt") system("mkdir docs") system("mkdir /docs") }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Can you help me rewrite this code in PHP instead of BBC_Basic, keeping it the same logically?
CLOSE #OPENOUT("output.txt") CLOSE #OPENOUT("\output.txt") *MKDIR docs *MKDIR \docs
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write the same code in PHP as shown below in Common_Lisp.
(import '(java.io File)) (.createNewFile (new File "output.txt")) (.mkdir (new File "docs")) (.createNewFile (File. (str (File/separator) "output.txt"))) (.mkdir (File. (str (File/separator) "docs")))
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write a version of this D function in PHP with identical behavior.
module fileio ; import std.stdio ; import std.path ; import std.file ; import std.stream ; string[] genName(string name){ string cwd = curdir ~ sep ; string root = sep ; name = std.path.getBaseName(name) ; return [cwd ~ name, root ~ name] ; } void Remove(string target){ if(exists(target)){ if (isfile(target)) std.file.remove(target); else std.file.rmdir(target) ; } } void testCreate(string filename, string dirname){ foreach(fn ; genName(filename)) try{ writefln("file to be created : %s", fn) ; std.file.write(fn, cast(void[])null) ; writefln("\tsuccess by std.file.write") ; Remove(fn) ; (new std.stream.File(fn, FileMode.OutNew)).close() ; writefln("\tsuccess by std.stream") ; Remove(fn) ; } catch(Exception e) { writefln(e.msg) ; } foreach(dn ; genName(dirname)) try{ writefln("dir to be created : %s", dn) ; std.file.mkdir(dn) ; writefln("\tsuccess by std.file.mkdir") ; Remove(dn) ; } catch(Exception e) { writefln(e.msg) ; } } void main(){ writefln("== test: File & Dir Creation ==") ; testCreate("output.txt", "docs") ; }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Rewrite the snippet below in PHP so it works the same as the original Delphi code.
program createFile; uses Classes, SysUtils; const filename = 'output.txt'; var cwdPath, fsPath: string; function CreateEmptyFile1: Boolean; var f: textfile; begin cwdPath := ExtractFilePath(ParamStr(0)) + '1_'+filename; AssignFile(f,cwdPath); Rewrite(f); Result := IOResult = 0; CloseFile(f); end; function CreateEmptyFile2: Boolean; var f: textfile; begin fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '2_'+filename; AssignFile(f,fsPath); Rewrite(f); Result := IOResult = 0; CloseFile(f); end; function CreateEmptyFile3: Boolean; var fs: TFileStream; begin cwdPath := ExtractFilePath(ParamStr(0)) + '3_'+filename; fs := TFileStream.Create(cwdPath,fmCreate); fs.Free; Result := FileExists(cwdPath); end; function CreateEmptyFile4: Boolean; var fs: TFileStream; begin fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '4_'+filename; fs := TFileStream.Create(fsPath,fmCreate); fs.Free; Result := FileExists(fsPath); end; begin if CreateEmptyFile1 then Writeln('File created at '+cwdPath) else Writeln('Error creating file at '+cwdPath); if CreateEmptyFile2 then Writeln('File created at '+fsPath) else Writeln('Error creating file at '+fsPath); if CreateEmptyFile3 then Writeln('File created at '+cwdPath) else Writeln('Error creating file at '+cwdPath); if CreateEmptyFile4 then Writeln('File created at '+fsPath) else Writeln('Error creating file at '+fsPath); Readln; end.
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Can you help me rewrite this code in PHP instead of Elixir, keeping it the same logically?
File.open("output.txt", [:write]) File.open("/output.txt", [:write]) File.mkdir!("docs") File.mkdir!("/docs")
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Maintain the same structure and functionality when rewriting this code in PHP.
-module(new_file). -export([main/0]). main() -> ok = file:write_file( "output.txt", <<>> ), ok = file:make_dir( "docs" ), ok = file:write_file( filename:join(["/", "output.txt"]), <<>> ), ok = file:make_dir( filename:join(["/", "docs"]) ).
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write a version of this F# function in PHP with identical behavior.
open System.IO [<EntryPoint>] let main argv = let fileName = "output.txt" let dirName = "docs" for path in ["."; "/"] do ignore (File.Create(Path.Combine(path, fileName))) ignore (Directory.CreateDirectory(Path.Combine(path, dirName))) 0
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Port the provided Factor code into PHP while preserving the original functionality.
USE: io.directories "output.txt" "/output.txt" [ touch-file ] bi@ "docs" "/docs" [ make-directory ] bi@
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Convert this Forth block to PHP, preserving its control flow and logic.
s" output.txt" w/o create-file throw drop s" /output.txt" w/o create-file throw drop
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Generate a PHP translation of this Fortran snippet without changing its computational steps.
PROGRAM CREATION OPEN (UNIT=5, FILE="output.txt", STATUS="NEW") CLOSE (UNIT=5) OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") CLOSE (UNIT=5) call system("mkdir docs/") call system("mkdir ~/docs/") END PROGRAM
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Produce a functionally identical PHP code for the snippet given in Groovy.
new File("output.txt").createNewFile() new File(File.separator + "output.txt").createNewFile() new File("docs").mkdir() new File(File.separator + "docs").mkdir()
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Can you help me rewrite this code in PHP instead of Haskell, keeping it the same logically?
import System.Directory createFile name = writeFile name "" main = do createFile "output.txt" createDirectory "docs" createFile "/output.txt" createDirectory "/docs"
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Transform the following J implementation into PHP, maintaining the same output and logic.
'' 1!:2 <'/output.txt' 1!:5 <'/docs'
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Rewrite the snippet below in PHP so it works the same as the original Julia code.
touch("output.txt") mkdir("docs") try touch("/output.txt") mkdir("/docs") catch e warn(e) end
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Ensure the translated PHP code behaves exactly like the original Lua snippet.
io.open("output.txt", "w"):close() io.open("\\output.txt", "w"):close()
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Keep all operations the same but rewrite the snippet in PHP.
SetDirectory@NotebookDirectory[]; t = OpenWrite["output.txt"] Close[t] s = OpenWrite[First@FileNameSplit[$InstallationDirectory] <> "\\output.txt"] Close[s] CreateDirectory["\\docs"] CreateDirectory[Directory[]<>"\\docs"]
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write a version of this MATLAB function in PHP with identical behavior.
fid = fopen('output.txt','w'); fclose(fid); fid = fopen('/output.txt','w'); fclose(fid); mkdir('docs'); mkdir('/docs');
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Transform the following Nim implementation into PHP, maintaining the same output and logic.
import os open("output.txt", fmWrite).close() createDir("docs") open(DirSep & "output.txt", fmWrite).close() createDir(DirSep & "docs")
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write the same code in PHP as shown below in OCaml.
# let oc = open_out "output.txt" in close_out oc;; - : unit = () # Unix.mkdir "docs" 0o750 ;; - : unit = ()
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Ensure the translated PHP code behaves exactly like the original Perl snippet.
use File::Spec::Functions qw(catfile rootdir); { open my $fh, '>', 'output.txt'; mkdir 'docs'; }; { open my $fh, '>', catfile rootdir, 'output.txt'; mkdir catfile rootdir, 'docs'; };
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write a version of this PowerShell function in PHP with identical behavior.
New-Item output.txt -ItemType File New-Item \output.txt -ItemType File New-Item docs -ItemType Directory New-Item \docs -ItemType Directory
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Rewrite this program in PHP while keeping its functionality equivalent to the R version.
f <- file("output.txt", "w") close(f) f <- file("/output.txt", "w") close(f) success <- dir.create("docs") success <- dir.create("/docs")
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Generate an equivalent PHP version of this Racket code.
#lang racket (display-to-file "" "output.txt") (make-directory "docs") (display-to-file "" "/output.txt") (make-directory "/docs")
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Transform the following COBOL implementation into PHP, maintaining the same output and logic.
identification division. program-id. create-a-file. data division. working-storage section. 01 skip pic 9 value 2. 01 file-name. 05 value "/output.txt". 01 dir-name. 05 value "/docs". 01 file-handle usage binary-long. procedure division. files-main. perform create-file-and-dir move 1 to skip perform create-file-and-dir goback. create-file-and-dir. call "CBL_CREATE_FILE" using file-name(skip:) 3 0 0 file-handle if return-code not equal 0 then display "error: CBL_CREATE_FILE " file-name(skip:) ": " file-handle ", " return-code upon syserr end-if call "CBL_CREATE_DIR" using dir-name(skip:) if return-code not equal 0 then display "error: CBL_CREATE_DIR " dir-name(skip:) ": " return-code upon syserr end-if . end program create-a-file.
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Rewrite this program in PHP while keeping its functionality equivalent to the REXX version.
options replace format comments java crossref symbols nobinary fName = ''; fName[0] = 2; fName[1] = '.' || File.separator || 'output.txt'; fName[2] = File.separator || 'output.txt' dName = ''; dName[0] = 2; dName[1] = '.' || File.separator || 'docs'; dName[2] = File.separator || 'docs' do loop i_ = 1 to fName[0] say fName[i_] fc = File(fName[i_]).createNewFile() if fc then say 'File' fName[i_] 'created successfully.' else say 'File' fName[i_] 'aleady exists.' end i_ loop i_ = 1 to dName[0] say dName[i_] dc = File(dName[i_]).mkdir() if dc then say 'Directory' dName[i_] 'created successfully.' else say 'Directory' dName[i_] 'aleady exists.' end i_ catch iox = IOException iox.printStackTrace end return
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Convert this Ruby block to PHP, preserving its control flow and logic.
File.write "output.txt", "" Dir.mkdir "docs" File.write "/output.txt", "" Dir.mkdir "/docs"
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Port the provided Scala code into PHP while preserving the original functionality.
import java.io.File fun main(args: Array<String>) { val filePaths = arrayOf("output.txt", "c:\\output.txt") val dirPaths = arrayOf("docs", "c:\\docs") var f: File for (path in filePaths) { f = File(path) if (f.createNewFile()) println("$path successfully created") else println("$path already exists") } for (path in dirPaths) { f = File(path) if (f.mkdir()) println("$path successfully created") else println("$path already exists") } }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Keep all operations the same but rewrite the snippet in PHP.
close [open output.txt w] close [open [file nativename /output.txt] w] file mkdir docs file mkdir [file nativename /docs]
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Convert this C++ block to Rust, preserving its control flow and logic.
#include <direct.h> #include <fstream> int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close(); _mkdir("docs"); _mkdir("/docs"); return 0; }
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Change the following Java code into Rust without altering its purpose.
import java.io.*; public class CreateFileTest { public static void main(String args[]) { try { new File("output.txt").createNewFile(); new File(File.separator + "output.txt").createNewFile(); new File("docs").mkdir(); new File(File.separator + "docs").mkdir(); } catch (IOException e) { System.err.println(e.getMessage()); } } }
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Write a version of this Go function in Rust with identical behavior.
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Write a version of this Rust function in Python with identical behavior.
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
Produce a functionally identical VB code for the snippet given in Rust.
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
Change the programming language of this snippet from C# to Rust without modifying what it does.
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Rewrite this program in Rust while keeping its functionality equivalent to the C version.
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME : &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) -> io::Result<File> where P: AsRef<Path> { let f_path = root.as_ref().join(FILE_NAME); let d_path = root.as_ref().join(DIR_NAME); DirBuilder::new().create(d_path).and(File::create(f_path)) } fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! { let _ = writeln!(&mut io::stderr(), "Error: {}", error); process::exit(code) }
Rewrite this program in C# while keeping its functionality equivalent to the Ada version.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
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; } } }
Maintain the same structure and functionality when rewriting this code in C.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
#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; }
Keep all operations the same but rewrite the snippet in C++.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
#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 a Go translation of this Ada snippet without changing its computational steps.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
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 a version of this Ada function in Java with identical behavior.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
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 Ada code snippet into Python without altering its behavior.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
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 Ada code snippet into VB without altering its behavior.
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix); end Decomposition;
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
Rewrite the snippet below in C so it works the same as the original AutoHotKey code.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
#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 the same code in C# as shown below in AutoHotKey.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
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; } } }
Maintain the same structure and functionality when rewriting this code in C++.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
#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 the following code from AutoHotKey to Java, ensuring the logic remains intact.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
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))); } }
Ensure the translated Python code behaves exactly like the original AutoHotKey snippet.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
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)
Preserve the algorithm and functionality while converting the code from AutoHotKey to VB.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
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 AutoHotKey function in Go with identical behavior.
Cholesky_Decomposition(A){ L := [], n := A.Count() L[1,1] := Sqrt(A[1,1]) loop % n { k := A_Index loop % n-1 { i := A_Index+1 Sigma := 0, j := 0 while (++j <= k-1) Sigma += L[i, j] * L[k, j] L[i, k] := (A[i, k] - Sigma) / L[k, k] Sigma := 0, j := 0 while (++j <= k-1) Sigma += (L[k, j])**2 L[k, k] := Sqrt(A[k, k] - Sigma) } } loop % n{ k := A_Index loop % n L[k, A_Index] := L[k, A_Index] ? L[k, A_Index] : 0 } return L } ShowMatrix(L){ for r, obj in L{ row := "" for c, v in obj row .= Format("{:.3f}", v) ", " output .= "[" trim(row, ", ") "]`n," } return "[" Trim(output, "`n,") "]" }
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() }
Generate a C translation of this BBC_Basic snippet without changing its computational steps.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
#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; }
Transform the following BBC_Basic implementation into C#, maintaining the same output and logic.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
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; } } }
Keep all operations the same but rewrite the snippet in C++.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
#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 BBC_Basic snippet to Java and keep its semantics consistent.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
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))); } }
Write the same algorithm in Python as shown in this BBC_Basic implementation.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
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 BBC_Basic implementation into VB, maintaining the same output and logic.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
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.
DIM m1(2,2) m1() = 25, 15, -5, \ \ 15, 18, 0, \ \ -5, 0, 11 PROCcholesky(m1()) PROCprint(m1()) PRINT @% = &2050A DIM m2(3,3) m2() = 18, 22, 54, 42, \ \ 22, 70, 86, 62, \ \ 54, 86, 174, 134, \ \ 42, 62, 134, 106 PROCcholesky(m2()) PROCprint(m2()) END DEF PROCcholesky(a()) LOCAL i%, j%, k%, l(), s DIM l(DIM(a(),1),DIM(a(),2)) FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO i% s = 0 FOR k% = 0 TO j%-1 s += l(i%,k%) * l(j%,k%) NEXT IF i% = j% THEN l(i%,j%) = SQR(a(i%,i%) - s) ELSE l(i%,j%) = (a(i%,j%) - s) / l(j%,j%) ENDIF NEXT j% NEXT i% a() = l() ENDPROC DEF PROCprint(a()) LOCAL row%, col% FOR row% = 0 TO DIM(a(),1) FOR col% = 0 TO DIM(a(),2) PRINT a(row%,col%); NEXT PRINT NEXT row% ENDPROC
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 Clojure to C, same semantics.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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 Clojure to C#, ensuring the logic remains intact.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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; } } }
Produce a language-to-language conversion: from Clojure to C++, same semantics.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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))); } }
Port the following code from Clojure to Python with equivalent syntax and logic.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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)
Maintain the same structure and functionality when rewriting this code in VB.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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
Port the provided Clojure code into Go while preserving the original functionality.
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec 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() }
Transform the following Common_Lisp implementation into C, maintaining the same output and logic.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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; }
Port the provided Common_Lisp code into C# while preserving the original functionality.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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; } } }
Convert this Common_Lisp block to C++, preserving its control flow and logic.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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; }
Convert this Common_Lisp block to Java, preserving its control flow and logic.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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 Common_Lisp.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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)
Convert the following code from Common_Lisp to VB, ensuring the logic remains intact.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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
Convert this Common_Lisp block to Go, preserving its control flow and logic.
(defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0))) (do ((k 0 (incf k))) ((> k (- n 1)) nil) (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum))))) (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil) (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k))))) 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() }
Maintain the same structure and functionality when rewriting this code in C.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
#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; }
Generate a C# translation of this D snippet without changing its computational steps.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
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 D to C++ with equivalent syntax and logic.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
#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 a version of this D function in Java with identical behavior.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
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))); } }
Write the same code in Python as shown below in D.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
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 D code.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
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 D snippet to Go and keep its semantics consistent.
import std.stdio, std.math, std.numeric; T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; } void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
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() }
Rewrite this program in C while keeping its functionality equivalent to the Delphi version.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
#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; }
Port the following code from Delphi to C# with equivalent syntax and logic.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
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; } } }
Translate this program into C++ but keep the logic exactly as in Delphi.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
#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.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
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 the snippet below in Python so it works the same as the original Delphi code.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
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)
Maintain the same structure and functionality when rewriting this code in VB.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
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 Delphi function in Go with identical behavior.
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if i=j then Result[i*n+j]:=Sqrt(a[i*n+i]-s) else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s); end; end; end; procedure ShowMatrix(a : array of Float); var i, j, n : Integer; begin n:=Round(Sqrt(a.Length)); for i:=0 to n-1 do begin for j:=0 to n-1 do Print(Format('%2.5f ', [a[i*n+j]])); PrintLn(''); end; end; var m1 := new Float[9]; m1 := [ 25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0 ]; var c1 := Cholesky(m1); ShowMatrix(c1); PrintLn(''); var m2 : array of Float := [ 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 ]; var c2 := Cholesky(m2); ShowMatrix(c2);
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() }
Change the programming language of this snippet from F# to C without modifying what it does.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
#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 language-to-language conversion: from F# to C#, same semantics.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
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 F# code.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
#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; }
Transform the following F# implementation into Java, maintaining the same output and logic.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
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))); } }
Port the following code from F# to Python with equivalent syntax and logic.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
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 F# implementation into VB, maintaining the same output and logic.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
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 algorithm in Go as shown in this F# implementation.
open Microsoft.FSharp.Collections let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1] (1.0 / l.[j, j]) * (a.[i, j] - sum) if j > i then 0.0 else if i = j then c1 j else c2 i j let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a) Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l l let printMat a = let arrow = (Array2D.length2 a |> float) / 2.0 |> int let c = cholesky a for row in 0..(Array2D.length1 a) - 1 do for col in 0..(Array2D.length2 a) - 1 do printf "%.5f,\t" a.[row, col] printf (if arrow = row then "--> \t" else "\t\t") for col in 0..(Array2D.length2 c) - 1 do printf "%.5f,\t" c.[row, col] printfn "" let ex1 = array2D [ [25.0; 15.0; -5.0]; [15.0; 18.0; 0.0]; [-5.0; 0.0; 11.0]] let ex2 = array2D [ [18.0; 22.0; 54.0; 42.0]; [22.0; 70.0; 86.0; 62.0]; [54.0; 86.0; 174.0; 134.0]; [42.0; 62.0; 134.0; 106.0]] printfn "ex1:" printMat ex1 printfn "ex2:" printMat ex2
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() }
Generate a C# translation of this Fortran snippet without changing its computational steps.
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
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 Fortran block to C++, preserving its control flow and logic.
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
#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 algorithm in C as shown in this Fortran implementation.
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
#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; }
Ensure the translated Java code behaves exactly like the original Fortran snippet.
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
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 Fortran block to Python, preserving its control flow and logic.
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
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)