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

- old
+ new

@@ -36,11 +36,11 @@ new_function.terms.reject! { |_,t| t.coefficient == 0 } return new_function end def roots - if terms.keys.none?(&:zero?) + if !terms.empty? and terms.keys.none?(&:zero?) self.alter { |nf, term| nf.terms[term.exponent-1].coefficient = term.coefficient }.roots << 0.0 else case self.degree when 1 Set[-self.terms[0].coefficient / self.terms[1].coefficient] @@ -59,11 +59,10 @@ def local_extrema derivative = self.derivative max_min_extremum = Hash.new { |hash,key| hash[key] = Set.new } 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 possible_extrema.zip(samples.each_cons(2)).each do |pe,(after,before)| @@ -75,24 +74,21 @@ end return max_min_extremum end def curvature_behaviour - if degree < 2 - return {} - else - extrema = self.derivative.extrema - curvature_behaviour = Hash.new {|h,k|h[k]=Set.new} - extrema.values.inject(&:|).sort.each_cons(2) do |start_point,end_point| - curvature_behaviour[AfterextremaCurvatureMapping[extrema.find { |k,v| v.include?(start_point) }.first]] << Range.new(start_point,end_point) - end + hash = Hash.new {|h,k|h[k]=Set.new} + extrema = self.derivative.extrema + extrema.values.inject(Set[],&:|).sort.each_cons(2).inject(hash) do |curvature_behaviour,(start_point,end_point)| + kind_of_curvature = AfterextremaCurvatureMapping[extrema.find { |k,v| v.include?(start_point) }.first] + curvature_behaviour[kind_of_curvature] << Range.new(start_point,end_point) + curvature_behaviour end - return curvature_behaviour end def degree - self.terms.keys.max + self.terms.keys.max || 0 end def to_s terms.delete_if { |_,t| t.coefficient.zero? }.sort_by { |_,t| -t.exponent }.inject("") do |string,(_,term)| string << term.to_s @@ -105,12 +101,14 @@ end def extrema extrema = local_extrema a = self.terms[self.degree].coefficient - max_or_min = (self.degree.even? ? [1,1] : [-1,1]).map { |n| (n * a)/a.abs } - extrema[MinMaxMapping[max_or_min.first]] << -1.0/0 - extrema[MinMaxMapping[max_or_min.last]] << 1.0/0 + unless self.degree == 0 + max_or_min = (self.degree.even? ? [1,1] : [-1,1]).map { |n| (n * a)/a.abs } + extrema[MinMaxMapping[max_or_min.first]] << -1.0/0 + extrema[MinMaxMapping[max_or_min.last]] << 1.0/0 + end return extrema end private