source: CIVL/examples/compare/CholeskyDecomposition/cholesky2.c@ cc9073d

1.23 2.0 acw/focus-triggers main test-branch
Last change on this file since cc9073d was 9765af0, checked in by Si Li <sili@…>, 10 years ago

add cholesky decomposition code

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@3337 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 1.3 KB
Line 
1/*
2 * Cholesky decomposition;
3 * Code from: https://rosettacode.org/wiki/Cholesky_decomposition#C
4 */
5
6#include <stdio.h>
7#include <stdlib.h>
8#include <math.h>
9
10double *cholesky(double *A, int n) {
11 double *L = (double*)calloc(n * n, sizeof(double));
12 if (L == NULL)
13 exit(EXIT_FAILURE);
14
15 for (int i = 0; i < n; i++)
16 for (int j = 0; j < (i+1); j++) {
17 double s = 0;
18 for (int k = 0; k < j; k++)
19 s += L[i * n + k] * L[j * n + k];
20 L[i * n + j] = (i == j) ?
21 sqrt(A[i * n + i] - s) :
22 (1.0 / L[j * n + j] * (A[i * n + j] - s));
23 }
24
25 return L;
26}
27
28void show_matrix(double *A, int n) {
29 for (int i = 0; i < n; i++) {
30 for (int j = 0; j < n; j++)
31 printf("%2.5f ", A[i * n + j]);
32 printf("\n");
33 }
34}
35
36int main() {
37 int n = 3;
38 double m1[] = {25, 15, -5,
39 15, 18, 0,
40 -5, 0, 11};
41 double *c1 = cholesky(m1, n);
42 show_matrix(c1, n);
43 printf("\n");
44 free(c1);
45
46 n = 4;
47 double m2[] = {18, 22, 54, 42,
48 22, 70, 86, 62,
49 54, 86, 174, 134,
50 42, 62, 134, 106};
51 double *c2 = cholesky(m2, n);
52 show_matrix(c2, n);
53 free(c2);
54
55 return 0;
56}
Note: See TracBrowser for help on using the repository browser.