/*
Output should reflect as follows:
Number of Engine Size: 5
x Values: Corresponding Values
1.5 , 110
2.0 , 130
2.4 , 245
3.0 , 290
3.6 , 310
1st Round: m = 11.996, c = 4.34, MSE = 53845
2nd Round: m = 22.145, c = 7.993, MSE = 38827.381
3th Round: m = 30.732, c = 11.066, MSE = 28091.485
4th Round: m = 37.999, c = 13.648, MSE = 20415.483
*/
#include <stdio.h>
#include <math.h>
#define MAXSIZE 100
float x[MAXSIZE], y[MAXSIZE], pred_y[MAXSIZE];
double m, c, Dm, Dc, MSE;
void predy (float m, float c, int times)
{
int i;
for (i = 0; i < times; i++)
{
pred_y[i] = m * x[i] + c;
}
}
float calc_dm (int times)
{
int i;
float sum, Dm;
double dm[MAXSIZE];
for (i = 0; i < times; i++)
{
dm[i] = x[i] * (y[i] - pred_y[i]);
}
for (i = 0; i < times; i++)
{
sum += dm[i];
}
Dm = (-2 / (float)times) * sum;
return Dm;
}
float calc_dc (int times)
{
int i;
float sum, Dc;
double dc[MAXSIZE];
for (i = 0; i < times; i++)
{
dc[i] = (y[i] - pred_y[i]);
}
for (i = 0; i < times; i++)
{
sum += dc[i];
}
Dc = (-2 / (float)times) * sum;
return Dc;
}
float calc_MSE (int times)
{
int i;
double e[MAXSIZE];
double sum = 0.0;
for (i = 0; i < times; i++)
{
e[i] = (y[i] - pred_y[i]) * (y[i] - pred_y[i]);
}
for (i = 0; i < times; i++)
{
sum = sum + e[i];
}
MSE = sum / 5.0;
return MSE;
}
int main() {
int i, times,j;
double pred_y[MAXSIZE];
float n = 0.01;
printf("Enter the number of Engine Size to be calculalted: ");
scanf("%d", ×);
for (i = 0; i < times; i ++)
{
printf("Enter the Engine Size for #%d: ", i + 1);
scanf("%f", &x[i]);
printf("Enter the corresponding CO2 Emission: ");
scanf("%f", &y[i]);
}
for (j = 0; j < 5 ; j++)
{
predy(m, c, times);
Dm = calc_dm(times);
Dc = calc_dc(times);
MSE = calc_MSE(times);
m = m - n * Dm;
c = c - n * Dc;
m = round(m * 1000)/ 1000;
c = round(c * 1000)/ 1000;
MSE = round(MSE * 1000)/ 1000;
printf ("Value of M: %.3f\n", m);
printf ("Value of C: %.3f\n", c);
printf ("Value of MSE: %.3f\n", MSE);
}
return 0;
}