Calculate the correlation coefficient
Mathematica 34 bytes
Here are a few ways to obtain the Pearson product moment correlation. They all produce the same result. From Dr. belisarius: 34 bytes
Dot@@Normalize/@(#-Mean@#&)/@{x,y}
Built-in Correlation function I: 15 chars
This assumes that x
and y
are lists corresponding to each variable.
x~Correlation~y
0.76909
Built-in Correlation function II: 31 chars
This assumes d is a list of ordered pairs.
d[[;;,1]]~Correlation~d[[;;,2]]
0.76909
The use of ;;
for All
thanks to A Simmons.
Relying on the Standard Deviation function: 118 115 chars
The correlation can be determined by:
s=StandardDeviation;
m=Mean;
n=Length@d;
x=d[[;;,1]];
y=d[[;;,2]];
Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1)
0.76909
Hand-rolled Correlation: 119 chars
Assuming x
and y
are lists...
s=Sum;n=Length@d;m@p_:=Tr@p/n;
(s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}]))
0.76909
PHP 144 bytes
<?
for(;fscanf(STDIN,'%f%f',$$n,${-$n});$f+=${-$n++})$e+=$$n;
for(;$$i;$z+=$$i*$a=${-$i++}-=$f/$n,$y+=$a*$a)$x+=$$i*$$i-=$e/$n;
echo$z/sqrt($x*$y);
Takes the input from STDIN, in the format provided in the original post. Result:
0.76909044055492
Using the vector dot product:
where are the input vectors adjusted downwards by and respectively.
Perl 112 bytes
/ /,$e+=$`,$f+=$',@v=($',@v)for@u=<>;
$x+=($_-=$e/$.)*$_,$y+=($;=$f/$.-pop@v)*$;,$z-=$_*$;for@u;
print$z/sqrt$x*$y
0.76909044055492
Same alg, different language. In both cases, new lines have been added for 'readability', and are not required. The only notable difference in length is the first line: the parsing of input.
Q
Assuming builtins are allowed and x,y data are seperate vectors (7 chars):
x cor y
If data are stored as orderded pairs, as indicated by David Carraher, we get (for 12 characters):
{(cor).(+)x}