All pastes #278631 Raw Edit

Untitled

public ruby v1 · immutable
·published 2006-12-14 07:01 UTC
rendered paste body
SUPER_DIGITS=["\342\201\260", "\302\271", "\302\262", "\302\263", "\342\201\264", "\342\201\265", "\342\201\266", "\342\201\267", "\342\201\270", "\342\201\271"]def superscript_ascii(n)  "^#{n}"enddef superscript_html(n)  "<sup>#{n}</sup>"enddef superscript_utf8(n)  result=""  n.to_s.each_byte{|b| result+=SUPER_DIGITS[b-?0]}  resultendclass Polynomial  attr :coefficients  protected :coefficients  def initialize(coefficients)    @coefficients=coefficients.clone    @coefficients.pop until @coefficients[-1]!=0 or @coefficients.empty?    @coefficients=[0] if @coefficients.empty?  end  def degree()    @coefficients.size-1  end  def +(op)    case op    when Numeric      Polynomial.new(Array.new(degree+1) {|i| coefficients[i]+op})    when Polynomial      Polynomial.new(Array.new([degree,op.degree].max+1) {|i| (coefficients[i] or 0) + (op.coefficients[i] or 0)})    end  end  def *(op)    case op    when Numeric      Polynomial.new(Array.new(degree+1) {|i| coefficients[i]*op})    when Polynomial      result=Array.new(degree+op.degree+1) {0}      coefficients.each_index do |i|        op.coefficients.each_index do |j|          result[i+j]+=coefficients[i]*op.coefficients[j]        end      end      Polynomial.new(result)    end  end  def **(exponent)    result=Polynomial.new([1])    exponent.times {result*=self}    result  end  def -(op)    self+op*-1  end  def compose(op)    result=Polynomial.new([0])    coefficients.each_index do |i|      if i==0        result+=coefficients[i]      else        result+=(op**i)*coefficients[i]      end    end    result  end  def [](value)    sum=0    @coefficients.each_index {|i| sum+=@coefficients[i]*value**i}    sum  end  def to_s(var="x")    string=""    @coefficients.each_index do |i|       v= case i         when 0           ""         when 1           "#{var}"         else           "#{var}#{superscript_utf8(i)}"         end      if @coefficients[i]==1 and i!=0        string="#{v}#{string}"      elsif @coefficients[i]==-1 and i!=0        string="-#{v}#{string}"      elsif @coefficients[i]!=0        string="#{@coefficients[i]}#{v}#{string}"      end      if i!=degree and @coefficients[i]>0        string="+#{string}"      end    end    string  end  def solve(y=0)    case degree    when 0      []    when 1      b,a=coefficients      [(y-b)/a]    when 2      c,b,a=coefficients      root=Math.sqrt(b*b-4*a*(c-y))      [(-b+root)/(2*a),(-b-root)/(2*a)]    end  endendp0=Polynomial.new([-1,-3,4]) # 4x^2-3x-1puts p0puts p0.compose(Polynomial.new([-4,1])) # compose with x-4, produces the translation by 4 along the x axis.puts p0+4 # Add constant 4, produces the translation by 4 along the y axis.