Created
June 13, 2017 09:17
-
-
Save isaaguilar/68c614a059d1a57320ae014dc6b5ce39 to your computer and use it in GitHub Desktop.
linear trendline equation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def trendline(x, y): | |
# y = mx + b, where m = slope and b = offset | |
return "f(x) = {0}x + {1}".format(slope(x, y), offset(x, y)) | |
def sum_xy(x, y): | |
s = float(0) | |
for i in range(len(x)): | |
s += x[i] * y[i] | |
return s | |
def sum(x): | |
s = float(0) | |
for i in range(len(x)): | |
s += x[i] | |
return s | |
def sum_of_square(x): | |
s = float(0) | |
for i in range(len(x)): | |
s += x[i]**2 | |
return s | |
def slope(x, y): | |
n = float(len(x)) | |
return (n * sum_xy(x, y) - (sum(x) * sum(y))) / (n * sum_of_square(x) - sum(x)**2) | |
def offset(x, y): | |
n = float(len(x)) | |
return (sum(y) - slope(x, y) * sum(x)) / n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment