303b48bcfaccb89098fabaa426f628d50323a2a3
[pspp-builds.git] / src / math / correlation.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "correlation.h"
20
21 #include <gsl/gsl_matrix.h>
22 #include <gsl/gsl_cdf.h>
23 #include <math.h>
24 #include <libpspp/misc.h>
25 #include "minmax.h"
26
27
28 double
29 significance_of_correlation (double rho, double w)
30 {
31   double t = w - 2;
32   t /= 1 - MIN (1, pow2 (rho));
33   t = sqrt (t);
34   t *= rho;
35   
36   if (t > 0)
37     return  gsl_cdf_tdist_Q (t, w - 2);
38   else
39     return  gsl_cdf_tdist_P (t, w - 2);
40 }
41
42 gsl_matrix *
43 correlation_from_covariance (const gsl_matrix *cv, const gsl_matrix *v)
44 {
45   size_t i, j;
46   gsl_matrix *corr = gsl_matrix_calloc (cv->size1, cv->size2);
47   
48   for (i = 0 ; i < cv->size1; ++i)
49     {
50       for (j = 0 ; j < cv->size2; ++j)
51         {
52           double rho = gsl_matrix_get (cv, i, j);
53           
54           rho /= sqrt (gsl_matrix_get (v, i, j))
55             * 
56             sqrt (gsl_matrix_get (v, j, i));
57           
58           gsl_matrix_set (corr, i, j, rho);
59         }
60     }
61   
62   return corr;
63 }