I have two vectors of floats, x and y, and I want to compute the Pearson correlation coefficients. As I have to do it on a lot of data (for instance 10 millions different vectors x and 20 thousand different vectors y), I am using C++, and more specifically the gsl_stats_correlation function from the GSL.
Here is my C++ code:
#include <iostream>
#include <vector>
using namespace std;
#include <gsl/gsl_vector.h>
#include <gsl/gsl_statistics.h>
int main (int argc, char ** argv)
{
vector<double> x, y;
size_t n = 5;
x.push_back(1.0); y.push_back(1.0);
x.push_back(3.1); y.push_back(3.2);
x.push_back(2.0); y.push_back(1.9);
x.push_back(5.0); y.push_back(4.9);
x.push_back(2.0); y.push_back(2.1);
for(size_t i=0; i<n; ++i)
printf ("x[%ld]=%.1f y[%ld]=%.1f\n", i, x[i], i, y[i]);
gsl_vector_const_view gsl_x = gsl_vector_const_view_array( &x[0], x.size() );
gsl_vector_const_view gsl_y = gsl_vector_const_view_array( &y[0], y.size() );
double pearson = gsl_stats_correlation( (double*) gsl_x.vector.data, sizeof(double),
(double*) gsl_y.vector.data, sizeof(double),
n );
printf ("Pearson correlation = %f\n", pearson);
return 0;
}
It compiles successfully (gcc -Wall -g pearson.cpp -lstdc++ -lgsl -lgslcblas -o pearson) but when I run it here is the output:
x[0]=1.0 y[0]=1.0
x[1]=3.1 y[1]=3.2
x[2]=2.0 y[2]=1.9
x[3]=5.0 y[3]=4.9
x[4]=2.0 y[4]=2.1
Pearson correlation = 1.000000
While obviously the results should not be exactly 1, as shown with the following R code:
x <- c(1.0,3.1,2.0,5.0,2.0); y <-c(1.0,3.2,1.9,4.9,2.1)
cor(x, y, method="pearson") # 0.99798
What am I missing?