Skip to content

Instantly share code, notes, and snippets.

@masawada
Created November 11, 2012 11:57
Show Gist options
  • Save masawada/4054694 to your computer and use it in GitHub Desktop.
Save masawada/4054694 to your computer and use it in GitHub Desktop.
最小二乗法を解くスクリプト
# linest.rb - 1次式の最小二乗法で傾きと切片、それぞれの誤差を算出するスクリプト
# Author: Masayoshi Wada
# Usage:
# data = [[x1,y1],[x2,y2],[x3,y3],[x4,y4],[x5,y5]...[xn,yn]]
# と値の組を入力すると
# a, b, uca(aの不確かさ), ucb(bの不確かさ)を出力します。
# なおy = a + bxとして作っているので、aが切片、bが傾きになります。
#
# あとはTerminalから
# $ ruby linest.rbでおk
data = []
# DON'T EDIT FROM HERE
def linest(data)
n = data.size
sx = sx2 = sy = sxy = v = 0
data.each{|p|
sx += p[0]
sx2 += p[0]**2
sy += p[1]
sxy += p[0]*p[1]
}
d = (n*sx2-sx**2).to_f
d1 = sy*sx2-sx*sxy
d2 = n*sxy-sx*sy
a = d1/d
b = d2/d
wa = d/sx2
wb = d/n
data.each{|p| v += ((a+p[0]*b)-p[1])**2 }
s = Math.sqrt(v.to_f/(n-2))
return {
:a => a,
:b => b,
:uca => s/Math.sqrt(wa),
:ucb => s/Math.sqrt(wb)
}
end
ret = linest(data)
print "a: ",ret[:a],"\n"
print "b: ",ret[:b],"\n"
print "uca: ",ret[:uca],"\n"
print "ucb: ",ret[:ucb],"\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment