Skip to content

Instantly share code, notes, and snippets.

@shinout
Created May 15, 2014 16:45
Show Gist options
  • Save shinout/2f75900e7bc3255ef994 to your computer and use it in GitHub Desktop.
Save shinout/2f75900e7bc3255ef994 to your computer and use it in GitHub Desktop.
least square (最小二乗法)
least_square = (dataset)->
n = dataset.length
sigma_xy = 0
sigma_x = 0
sigma_y = 0
sigma_xsq = 0
for data in dataset
x = data[0]
y = data[1]
sigma_xy += x*y
sigma_x += x
sigma_y += y
sigma_xsq += x * x
a = (n * sigma_xy - sigma_x * sigma_y)/(n * sigma_xsq - sigma_x * sigma_x)
b = (sigma_xsq * sigma_y - sigma_xy * sigma_x)/(n * sigma_xsq - sigma_x * sigma_x)
return [a,b]
module.exports = least_square
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment