首页 > 解决方案 > 用 Ruby 拟合幂律

问题描述

我有这些数据,需要像在 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, b = %f\n", A, b2)
graph([x, y], [x2, A*Sf::exp(b2*x2)], "-C -g 3 -S 4")

在此处输入图像描述

标签: rubycurve-fittinggsl

解决方案


我解决了这个

 x = [  [1, 2, 3, 4], [1,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

推荐阅读