Skip to content

Instantly share code, notes, and snippets.

@benwilson512
Last active December 22, 2015 22:59
Show Gist options
  • Save benwilson512/6543991 to your computer and use it in GitHub Desktop.
Save benwilson512/6543991 to your computer and use it in GitHub Desktop.
Linear regression for a set of points. of the form [{x1, y1}, {x2, y2}] etc. I iterate through the point array several times which is unfortunate. The alternative was to try to iterate once and build several different states simultaneously, but this was at least prima facie easier.
# http://en.wikipedia.org/wiki/Simple_linear_regression
defmodule Exchange.Calc do
def linear_regression(points) do
n = length(points)
# Average of sum of products
sop_bar = sum_of_products(points) / n
# Average of sum of x and y respectively
{x_bar, y_bar} = points
|> sum
|> average(n)
# Average sum of x^2
x_sqr_bar = sum_of_x_squared(points) / n
slope = (
(sop_bar - x_bar * y_bar) /
(x_sqr_bar - x_bar * x_bar)
)
intercept = y_bar - slope * x_bar
fn(x) -> slope * x + intercept end
end
def sum_of_products(points) do
Enum.reduce(points, 0, fn ({x, y}, sum) -> sum + x * y end )
end
def sum_of_x_squared(points) do
Enum.reduce(points, 0, fn ({x, _y}, sum) -> sum + x * x end )
end
def average({x, y}, n) do
{x / n, y / n}
end
def sum(points) do
Enum.reduce(points, fn ({x1, y1}, {x2, y2}) -> {x1 + x2, y1 + y2} end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment