问题描述
我有这些数据,需要像在 Excel 中那样执行“幂律曲线拟合”。
我尝试过使用 Ruby/GSl,但只有“指数拟合”。您知道适合功率曲线的库或其他东西吗?
文档:https://blackwinter.github.io/rb-gsl/rdoc/fit_rdoc.html#label-Exponential+fitting
# Fitting
a2,b2,= Fit.linear(x,Sf::log(y))
x2 = Vector.linspace(0,5,20)
A = Sf::exp(a2)
printf("Expect: a = %f,b = %f\n",a,b)
printf("Result: a = %f,A,b2)
graph([x,y],[x2,A*Sf::exp(b2*x2)],"-C -g 3 -S 4")
解决方法
我用这个解决了
x = [ [1,2,3,4],[1,1,1] ]
y = [3,5,7,9]
# Y = Cx^b
# Log10 Y = Log C + b * Log X
def regression_coefficients y,x
y = Matrix.column_vector y.map { |i| i.to_f }
x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}
(x.t * x).inverse * x.t * y
end