Skip to content

Instantly share code, notes, and snippets.

@albedozero
Created February 24, 2022 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albedozero/e256aa19735e5b0f9218645cfdea8882 to your computer and use it in GitHub Desktop.
Save albedozero/e256aa19735e5b0f9218645cfdea8882 to your computer and use it in GitHub Desktop.
Quick script for calculating linear fit with uncertainty from x, y values
import sys
import numpy as np
class LinFit:
def __init__(self, x, y):
d = x.size * np.sum(x ** 2) - np.sum(x) ** 2
self.intercept = (np.sum(x ** 2) * np.sum(y) - np.sum(x) * np.sum(x * y)) / d
self.slope = (x.size * np.sum(x * y) - np.sum(x) * np.sum(y)) / d
self.s_y = np.sqrt(np.sum((y - self.intercept - self.slope * x) ** 2) / (x.size - 2))
self.s_intercept = self.s_y * np.sqrt(np.sum(x ** 2) / d)
self.s_slope = self.s_y * np.sqrt(x.size / d)
if __name__ == "__main__":
if len(sys.argv) > 1:
data = np.loadtxt('linreg.py', delimiter=',')
else:
data = np.loadtxt(__file__, delimiter=',', skiprows=30, comments='"')
fit = LinFit(data[:,0], data[:,1])
print("Linear fit results:")
print(f" slope: {fit.slope} +/- {fit.s_slope}")
print(f" intercept: {fit.intercept} +/- {fit.s_intercept}")
print(f" y uncertainty: {fit.s_y}")
# How to use:
# python linreg.py <data-file>
# where <data-file> is comma-separated x- and y-values
# or paste the values below, between the triple-quotes
"""
0.6,3
1.1,16
1.6,12
2.1,20
2.6,42
3.1,37
3.6,53
4.1,56
4.6,54
5.1,75
5.6,80
6.1,91
6.6,104
7.1,94
7.6,107
8.1,118
8.6,130
9.1,133
9.6,136
10.1,152
10.6,147
11.1,159
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment