lib/polynomials.rb in polynomials-0.1.5 vs lib/polynomials.rb in polynomials-0.1.6

- old
+ new

@@ -1,9 +1,11 @@ require 'set' require_relative 'term' require_relative 'core_ext/math' + class Polynomial + MinMaxMapping = { 1.0 => :max, -1.0 => :min } AfterextremaCurvatureMapping = { max: :right, min: :left } NegPosMinMaxExtremumMapping = {[1.0,-1.0] => :max,[-1.0,1.0] => :min} attr_accessor :terms @@ -33,18 +35,10 @@ end new_function.terms.reject! { |_,t| t.coefficient == 0 } return new_function end - def alter - new_function = self.class.new - self.terms.values.each do |term| - yield new_function, term - end - return new_function - end - def roots if terms.keys.none?(&:zero?) self.alter { |nf, term| nf.terms[term.exponent-1].coefficient = term.coefficient }.roots << 0.0 else case self.degree @@ -63,12 +57,12 @@ end def local_extrema derivative = self.derivative max_min_extremum = Hash.new { |hash,key| hash[key] = Set.new } - unless derivative.degree == 0 - possible_extrema = derivative.roots.sort + possible_extrema = derivative.roots.sort + unless possible_extrema.empty? samples = ([possible_extrema.first - 1] + possible_extrema.sort + [possible_extrema.last + 1]).each_cons(2).map do |before,after| (before + after)/2 end @@ -118,13 +112,24 @@ extrema[MinMaxMapping[max_or_min.last]] << 1.0/0 return extrema end private + def coefficients_till(n) coefficients = [] (0..n).each do |e| coefficients << self.terms[e].coefficient end return coefficients.reverse + end + + protected + + def alter + new_function = self.class.new + self.terms.values.each do |term| + yield new_function, term + end + return new_function end end