hqt

workshop 9 - bai 2 - HQT

hqt
Jul 26th, 2012
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. #include <stdio.h>
  2. #define MAX 100
  3.  
  4. int main(){
  5.     int sum = 0;
  6.     int x[MAX], y[MAX];
  7.     double mx=0.0, my=0.0;
  8.     int i = 0;
  9.     char filename[80];
  10.  
  11.     printf("Regression Analysis Calculator\n");
  12.     printf("==============================\n");
  13.  
  14.     printf("Enter the name of the data file: "); scanf("%s",filename);
  15.     FILE * f;
  16.     f = fopen(filename, "r");
  17.     if (f == NULL){
  18.         printf("Cannot open file\n");
  19.         return;
  20.     }
  21.     while (!feof(f)){
  22.         fscanf(f,"%d",&x[sum]);
  23.         fscanf(f,"%d",&y[sum]);
  24.         mx += x[sum]; my +=y[sum];
  25.         sum++;
  26.     }
  27.     mx /= n;
  28.     my /= n;
  29.     fclose(f);
  30.  
  31.     // find slope(t)
  32.     float t = 0.0;
  33.     float ts =0.0, ms = 0.0;
  34.     for(i=0; i<sum; i++){
  35.         ts += (x[i] - mx)*(y[i] - my);
  36.         ms += (x[i] - mx)*(x[i] -mx);
  37.     }
  38.     t = ts/ms;
  39.    
  40.     // y-intercept (b)
  41.     float b = my - t*mx;
  42.    
  43.     // find sx and sy
  44.     float sx = 0.0, sy=0.0;
  45.     for(i=0; i<sum; i++){
  46.         sx +=  x[i]*x[i];
  47.         sy +=  y[i]*y[i];
  48.     }
  49.    
  50.     // d : standard deviation
  51.     float dx = ( sx / n ) - mx*mx;
  52.     float dy = ( sy / n ) - my*my;
  53.    
  54.     // correlation coefficient : r = { [ (x1y1) + (x2y2) + ... + (xnyn) ] / n - mx my} / [ dx dy ]
  55.     float r = 0.0;
  56.     float p1 = 0.0;
  57.     for(i=0; i<sum; i++){
  58.         p1 += x[i]*y[i];
  59.     }
  60.     r = (p1/sum - mx*my) / (dx*dy);
  61.    
  62.     printf("The number of data values read from this file was %d\n", sum);
  63.     printf("The slope of the least squares fit is : %f",t);
  64.     printf("The y-intercept of the least squares fit is : %f",b);
  65.     printf("The correlation coefficient is: %f", r);
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment