Class: Maxima::Polynomial

Inherits:
Unit
  • Object
show all
Defined in:
lib/maxima/polynomial.rb

Instance Attribute Summary

Attributes inherited from Unit

#maxima_output, #plot_title

Class Method Summary collapse

Methods inherited from Unit

#==, #===, #at, #gnu_plot_options, #gnu_plot_text, #gnu_plot_w, #imaginary?, #initialize, #inspect, #negative?, parse, parse_float, #positive?, #real?, #simplified, #through_maxima, #to_f, #to_gnu_plot, #to_maxima_input, #to_pdf, #to_s, #with_plot_title, #zero?

Constructor Details

This class inherits a constructor from Maxima::Unit

Class Method Details

.fit(histogram, degrees) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/maxima/polynomial.rb', line 4

def self.fit(histogram, degrees)
  throw :degrees_must_be_zero_or_positive if degrees < 0

  equation_string, variables = polynomial_equation(degrees)
  results = Maxima.lsquares_estimation(histogram.to_a, [:x, :y], "y = #{equation_string}", variables)

  function = Maxima::Function.new(equation_string)

  {
    mse:      results.delete(:mse),
    function: function.at(results),
  }
end

.polynomial_equation(degrees, f_of: "x") ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/maxima/polynomial.rb', line 18

def self.polynomial_equation(degrees, f_of: "x")
  polynomials, constant_variables = [], []

  (degrees + 1).times.each do |degree|
    constant_variable = "c#{degree}"
    constant_variables << constant_variable

    case degree
    when 0
      polynomials << constant_variable
    when 1
      polynomials << "#{constant_variable} * #{f_of}"
    else
      polynomials << "#{constant_variable} * #{f_of} ^ #{degree}"
    end
  end

  [
    polynomials.join(" + "),
    constant_variables
  ]
end