creat a linear regression equation in javascript

index.tsx
// Sample data points
const points = [
    { x: 1, y: 2 },
    { x: 2, y: 3 },
    { x: 3, y: 4 },
    { x: 4, y: 5 },
    { x: 5, y: 6 }
];

// Calculate the mean of x and y values
const mean = (data, key) => data.reduce((acc, point) => acc + point[key], 0) / data.length;
const xMean = mean(points, 'x');
const yMean = mean(points, 'y');

// Calculate slope (m) of the regression line
const numerator = points.reduce((acc, point) => acc + (point.x - xMean) * (point.y - yMean), 0);
const denominator = points.reduce((acc, point) => acc + Math.pow(point.x - xMean, 2), 0);
const m = numerator / denominator;

// Calculate y-intercept (c) of the regression line
const c = yMean - m * xMean;

// Print the linear regression equation
console.log(`y = ${m}x + ${c}`);
765 chars
25 lines

This code calculates the linear regression equation (y = mx + c) for a set of sample data points containing x and y values. The equation is printed to the console.

related categories

gistlibby LogSnag