Cholesky Decomposition in C++

I have a source code to compute Cholesky Decomposition in C++. But I can get true result. Thank for editing for me.

#include <iostream>
#include <cmath>

using namespace std;

double **Cholesky_Decomposition(double **p, long m, long n);
double **Create2DArray(long rows, long columns);
void Output2DArray(double **p, long rows, long columns);

// Cholesky_Decomposition returns the Cholesky Decomposition Matrix.
double **Cholesky_Decomposition(double **p, long m, long n)
// Licensing: It is closed and private code.
{
long i, j, k; double temp = 0, temp2 = 0;
if (m != n)
{
cout << "Matrix is not square";
exit(1);
}
// Initialize and populate matrix L which will be the lower Cholesky
double **L = Create2DArray(m, n);
for (i = 0; i < m; i++)
for (j = 0; j < m; j++)
{
temp = 0; temp2 = 0;
if (i > j)
{
if (j > 0)
{
for (k = 1; k < j + 1; k++)
temp2 += (L[i][k - 1] * L[j][k - 1]);
}
L[i][j] = (p[i][j] - temp2) / L[j][j];
}
else if (i == j)
{
for (k = 0; k < i; k++)
temp += pow(L[i][k], 2);
L[i][j] = sqrt(p[i][j] - temp);
}
else
L[i][j] = 0;
}
return L;
}

// Create2DArray ia a function that creates a reference (double) dynamic 2D-Array
// using Pointer.
double **Create2DArray(long rows, long columns)
// Licensing: It is closed code.
// Modified Date: 22 Feb 2015
// Author: Huynh Ngoc Vinh, Ho Chi Minh City, Viet Nam
{
double **p = new (nothrow) double *[rows];
for (long i = 0; i < rows; i++) p[i] = new (nothrow) double[columns];
return p;
}

// Output1DArray is a function that prints out the value of 1D-Array.
void Output2DArray(double **p, long rows, long columns)
// Licensing: It is closed code.
// Modified Date: 06 Aug 2015.
// Author: Huynh Ngoc Vinh, Ho Chi Minh City, Viet Nam
{
cout << "2D-matrix: ";
for (long i = 0; i < rows; i++)
{
cout << "\n";
for (long j = 0; j < columns; j++)
cout << p[i][j] << "\t";
}
cout << "\n";
}

void main()
{
double **a = Create2DArray(5, 5);
a[0][0] = 18;
a[0][1] = 22;
a[0][2] = 54;
a[0][3] = 42;
a[0][4] = 48;
a[1][0] = 22;
a[1][1] = 70;
a[1][2] = 86;
a[1][3] = 62;
a[1][4] = 49;
a[2][0] = 54;
a[2][1] = 86;
a[2][2] = 174;
a[2][3] = 134;
a[2][4] = 38;
a[3][0] = 42;
a[3][1] = 62;
a[3][2] = 134;
a[3][3] = 106;
a[3][4] = 92;
a[4][0] = 15;
a[4][1] = 85;
a[4][2] = 14;
a[4][3] = 36;
a[4][4] = 78;
a = Cholesky_Decomposition(a, 5, 5);
Output2DArray(a, 5, 5);
system("pause");
}
Topic archived. No new replies allowed.