Print y = mx + b
In this step, you'll learn how to print the linear regression equation and predict y values using the computed slope and intercept.
Update the linear_regression.c
file to add prediction functionality:
cd ~/project
nano linear_regression.c
Replace the previous code with the following implementation:
#include <stdio.h>
#include <math.h>
#define MAX_POINTS 100
typedef struct {
double x;
double y;
} DataPoint;
void computeLinearRegression(DataPoint points[], int num_points, double *m, double *b) {
double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x_squared = 0;
for (int i = 0; i < num_points; i++) {
sum_x += points[i].x;
sum_y += points[i].y;
sum_xy += points[i].x * points[i].y;
sum_x_squared += points[i].x * points[i].x;
}
double n = num_points;
*m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x * sum_x);
*b = (sum_y - (*m) * sum_x) / n;
}
// Function to predict y value
double predictY(double m, double b, double x) {
return m * x + b;
}
int main() {
DataPoint points[MAX_POINTS];
int num_points = 0;
printf("Enter x and y coordinates (enter -1 -1 to finish):\n");
while (num_points < MAX_POINTS) {
double x, y;
scanf("%lf %lf", &x, &y);
if (x == -1 && y == -1) {
break;
}
points[num_points].x = x;
points[num_points].y = y;
num_points++;
}
double slope, intercept;
computeLinearRegression(points, num_points, &slope, &intercept);
printf("\nLinear Regression Equation:\n");
printf("y = %.4fx + %.4f\n", slope, intercept);
// Print prediction for sample x values
printf("\nPredicted y values:\n");
double test_x_values[] = {0, 2.5, 6, 10};
for (int i = 0; i < 4; i++) {
double predicted_y = predictY(slope, intercept, test_x_values[i]);
printf("When x = %.2f, y = %.4f\n", test_x_values[i], predicted_y);
}
return 0;
}
Compile the program:
gcc -o linear_regression linear_regression.c -lm
Run the program with sample data points:
./linear_regression
Example output:
Enter x and y coordinates (enter -1 -1 to finish):
1 2
2 4
3 5
4 4
5 5
-1 -1
Linear Regression Equation:
y = 0.6000x + 2.2000
Predicted y values:
When x = 0.00, y = 2.2000
When x = 2.50, y = 3.7000
When x = 6.00, y = 5.8000
When x = 10.00, y = 8.2000
Key points about printing the regression equation:
- We added a
predictY()
function to calculate y for any given x
- The main function prints the full equation: y = mx + b
- We demonstrate prediction by showing y values for different x inputs
- The output provides a clear visualization of the linear regression model