waltermilner

Untitled

Mar 29th, 2016
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int compare (const void * a, const void * b)
  5. {
  6.     if (*(double *)a > *(double *)b) return 1;
  7.     if (*(double *)a < *(double *)b ) return -1;
  8.  
  9.     return 0;
  10. }
  11.  
  12. int main()
  13. {
  14.     double X[] = { 62.0,53.0,51.0,25.0,79.2,23.7,47.9,24.1 };
  15.     double Y[] = { 52,64.5,39.9,34,21.5,37,39,65.8 };
  16.     const int LENGTH=8;
  17.     // copy arrays
  18.     double origX[LENGTH];
  19.     double origY[LENGTH];
  20.     for (int i=0; i<LENGTH; i++)
  21.     {
  22.         origX[i]=X[i];
  23.         origY[i]=Y[i];
  24.     }
  25.     qsort(X, LENGTH, sizeof(double), compare);
  26.     qsort(Y, LENGTH, sizeof(double), compare);
  27.     printf("Sorted data\n");
  28.     for (int i=0; i<LENGTH; i++)
  29.         printf("%d %f %f\n",i, X[i], Y[i]);
  30.     // replace values by ranks    
  31.     for (int i=0; i<LENGTH; i++)
  32.     {
  33.         double val = origX[i];
  34.         for (int j=0; j<LENGTH; j++)
  35.         {
  36.             if (X[j]==val)
  37.             {
  38.                 origX[i]=j;
  39.                 break;
  40.             }
  41.         }
  42.         val = origY[i];
  43.         for (int j=0; j<LENGTH; j++)
  44.         {
  45.             if (Y[j]==val)
  46.             {
  47.                 origY[i]=j;
  48.                 break;
  49.             }
  50.         }
  51.     }
  52.     printf("Ranks\n");
  53.     for (int i=0; i<LENGTH; i++)
  54.         printf("%d %f %f \n",i, origX[i], origY[i]);
  55.     // form sum of difference in rank, squared
  56.     int sumD2=0;
  57.     for (int i=0; i<LENGTH; i++)
  58.     {
  59.         int d = (int)(origX[i]-origY[i]);
  60.         sumD2+=d*d;
  61.     }
  62.     // r = 1 - 6 sunD2 / (n^3-n)
  63.     double r = 1 - 6.0*sumD2/ (LENGTH*(LENGTH*LENGTH-LENGTH));
  64.     printf("Pearson's rank = %f\n", r);
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment