Search code examples
rubycurve-fittinggsl

Power law fitting with Ruby


I have this data and need to perform a "power law curve fitting" as I did in Excel.

I have tried using Ruby/GSl but there is only "exponential fitting". Do you know a library or something else to fit in a power curve?

Doc: 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")

enter image description here


Solution

  • I solved with this

     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