module Polynomials class Polynomial include Analyzable attr_accessor :terms def self.parse(string) polynomial = self.new string.split(/(?=[-+])/).each do |term| parsed = Term.parse(term) polynomial.terms[parsed.exponent].coefficient += parsed.coefficient end return polynomial end def initialize(*args) self.terms = Hash.new { |hash, key| hash[key] = Term.new(key) } unless args.empty? args.reverse.each.with_index do |coefficient,exponent| self.terms[exponent].coefficient += coefficient end end end def calculate(x) self.terms.values.inject(0.0) do |acc,t| acc + (t.coefficient.to_f * (x**t.exponent)) end end alias call calculate def derivative new_function = self.alter do |nf, term| (nf.terms[term.exponent - 1].coefficient += term.exponent * term.coefficient) unless term.exponent.zero? end end def roots if !terms.empty? and (terms.keys.none?(&:zero?) || terms[0].coefficient.zero?) self.alter { |nf, term| nf.terms[term.exponent-self.lt.exponent].coefficient = term.coefficient }.roots << Root.new(0.0) else case self.degree when 1 Set[-self.terms[0].coefficient / self.terms[1].coefficient] when 2 Formulas.roots_of_quadratic_function(*coefficients_till(2)) when 3 Formulas.roots_of_cubic_function(*coefficients_till(3)) when 4 Formulas.roots_of_quartic_function(*coefficients_till(4)) else Set[] end.map { |x| Root.new(x) }.to_set end end def degree self.terms.keys.max || 0 end def to_s terms.sort_by { |_,t| -t.exponent }.inject("") do |string,(_,term)| string << term.to_s unless term.coefficient.zero? && !term.exponent.zero? string end.strip.sub(/\A\+\s/, '') end def ==(other) delete_zeros = proc{ |_,t| t.coefficient.zero? } self.terms.delete_if(&delete_zeros) == other.terms.delete_if(&delete_zeros) end def gt self.terms[self.degree] end def lt self.terms[self.terms.reject { |_,t| t.coefficient.zero? }.min_by{ |_,t| t.exponent}.first] end def pointset(start,stop,step=0.1) data = [] x = start while x < stop data << [x,self.(x)] x += step end data << [stop,self.(stop)] end def grouped_pointset(start,stop,step=0.1,grouped) Hash[grouped.map do |key,intervals| intervals = intervals.reject { |s,e| e < start || s > stop } intervals = intervals.map do |s,e| self.pointset([s,start].max, [e,stop].min, step) end [key,intervals] end] end def coefficients_till(n) coefficients = [] (0..n).each do |e| coefficients << self.terms[e].coefficient end return coefficients.reverse end private :coefficients_till def alter new_function = self.class.new self.terms.values.each do |term| yield new_function, term end return new_function end protected :alter end end