Skip to content
🛠️ToolsShed

Linear Regression Calculator

Calculate linear regression from data points: slope, intercept, R², and predictions.

#XY
1
2
3
4
5

About this tool

Linear regression is a fundamental statistical method that models the relationship between two variables by fitting a straight line through a set of data points. This calculator helps you find the best-fit line, compute the slope and intercept, and measure how well your data follows a linear pattern through the R² value. Whether you're analyzing trends in sales data, comparing experimental results, or exploring correlations in scientific studies, understanding linear relationships is essential for data-driven decision making.

To use this tool, simply enter your data points as pairs of X and Y values, then click Calculate to instantly obtain the slope (the rate of change), the intercept (where the line crosses the Y-axis), the R² coefficient (a measure of fit quality from 0 to 1, where 1 means perfect fit), and prediction equations. The tool also lets you input a new X value to forecast the corresponding Y prediction based on the fitted model.

This calculator is ideal for students learning statistics, researchers validating hypotheses, and professionals identifying trends in business metrics. Keep in mind that linear regression assumes your relationship is roughly linear; if your data shows a curved pattern or wide scatter, the model may not be reliable. For more complex relationships, consider polynomial or other non-linear regressions.

Frequently Asked Questions

Code Implementation

def linear_regression(x: list, y: list) -> dict:
    n = len(x)
    if n < 2:
        raise ValueError("Need at least 2 data points")
    sum_x = sum(x)
    sum_y = sum(y)
    sum_xy = sum(xi * yi for xi, yi in zip(x, y))
    sum_x2 = sum(xi ** 2 for xi in x)
    mean_x = sum_x / n
    mean_y = sum_y / n

    slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
    intercept = mean_y - slope * mean_x

    # R-squared
    ss_res = sum((yi - (slope * xi + intercept)) ** 2 for xi, yi in zip(x, y))
    ss_tot = sum((yi - mean_y) ** 2 for yi in y)
    r2 = 1 - ss_res / ss_tot if ss_tot != 0 else 1.0

    return {"slope": slope, "intercept": intercept, "r_squared": r2,
            "pearson_r": r2 ** 0.5 if r2 >= 0 else 0}

x = [1, 2, 3, 4, 5]
y = [2.1, 3.9, 6.2, 7.8, 10.1]
result = linear_regression(x, y)
print(f"y = {result['slope']:.4f}x + {result['intercept']:.4f}")
print(f"R² = {result['r_squared']:.4f}")

# Predict
x_new = 6
y_pred = result['slope'] * x_new + result['intercept']
print(f"Prediction at x=6: {y_pred:.2f}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.