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
17
18
19
20
# File 'lib/maxima/polynomial.rb', line 4

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

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

  results.each do |variable, value|
    equation_string.gsub!("(#{variable})", value.to_s)
  end

  {
    function: Maxima::Function.new(equation_string).simplified,
    mse: mse
  }
end

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/maxima/polynomial.rb', line 22

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

  degrees.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