Você está na página 1de 3

Solution to Problem Set 2 Question No.

1 :

Program:

/* Program to accept a set of bivariate data , calculate the simple correlation coefficient ,
display the two regression equations and find regressed values of y given x and vice-versa */

#include<stdio.h>
#include<math.h>

void main()
{
int i,n,X_n,Y_n;
float x,y,sum1_x,sum2_x,sum1_y,sum2_y,prod_xy,mean_x,mean_y,var_x,var_y,
var_xy,r,b_yx,b_xy,reg_x[30],reg_y[30],X[30],Y[30]
char c,flag;

clrscr();

do
{
printf("Enter the number of paired observations:");
scanf("%d",&n);
}
while( n < 1);

sum1_x=sum2_x=sum1_y=sum2_y=prod_xy=0;

for( i = 0; i < n; i++)


{
printf("\nEnter the x value of pair %d:",i+1);
scanf("%f",&x);
printf("\nEnter the y value of pair %d:",i+1);
scanf("%f",&y);
sum1_x = sum1_x + x;
sum1_y = sum1_y + y;
sum2_x = sum2_x + pow(x,2);
sum2_y = sum2_y + pow(y,2);
prod_xy = prod_xy + x * y;
}

mean_x = sum1_x/n;
mean_y = sum1_y/n;
var_x = sum2_x/n - pow(mean_x,2);
var_y = sum2_y/n - pow(mean_y,2);
var_xy = prod_xy/n -mean_x * mean_y;
r = var_xy/sqrt(var_x * var_y);
b_yx = var_xy/var_x;
b_xy = var_xy/var_y;

printf("\nThe value of the simple correlation coefficient between x and y is %f",r);


printf("\nThe regressed line of y on x is Y = %f + %fx",mean_y-b_yx*mean_x,b_yx);
printf("\nThe regressed line of x on y is X = %f + %fy",mean_x-b_xy*mean_y,b_xy);
printf("\nDo you want to find predicted values from given data set? Enter y is yes
otherwise n:");
scanf("%s",&flag);

if( flag == 'y')


{
do
{
printf("\nEnter the variable whose value you want to predict :");
scanf("%s",&c);
if( c == 'y')
{
do
{
printf("\nEnter the number of x values for which you want
to predict y(<=30):");
scanf("%d",&Y_n);
if(Y_n < 1 || Y_n > 30)
{
printf("INVALID ENTRY");
}
}
while( Y_n < 1 || Y_n > 30);
for( i = 0; i < Y_n; i++)
{
printf("\nEnter the value of x :");
scanf("%f",&reg_x[i]);
Y[i] = mean_y + b_yx*(reg_x[i] - mean_x);
}
printf("\nPredictor value(x) Predicted value(Y)");
for( i = 0; i < Y_n; i++)
{
printf("\n%f %f",reg_x[i],Y[i]);
}
printf("\nDo you want to calculate predicted values for a new data
set? Enter y if yes otherwise n :");
scanf("%s",&flag);

}
else if( c == 'x')
{
do
{
printf("\nEnter the number of y values for which you want
to predict x:");
scanf("%d",&X_n);
if(X_n < 1 || X_n > 30)
{
printf("INVALID ENTRY");
}
}
while( X_n < 1 || X_n > 30);
for( i = 0; i < X_n; i++)
{
printf("\nEnter the value of y :");
scanf("%f",&reg_y[i]);
X[i] = mean_x + b_xy*(reg_y[i] - mean_y);
}
printf("\nPredictor value(y) Predicted value(X)");
for( i = 0; i < X_n; i++)
{
printf("\n%f %f",reg_y[i],X[i]);
}
printf("\nDo you want to calculate predicted values for a new data
set? Enter y if yes otherwise n :");
scanf("%s",&flag);
}
else
{
printf("\nINVALID ENTRY");
}
}
while( flag == 'y');
}

getch();

Você também pode gostar