lib/hpsqrt.rb in hpsqrt-1.8.0 vs lib/hpsqrt.rb in hpsqrt-1.9.0

- old
+ new

@@ -71,11 +71,11 @@ self.class.new(terms) end def /(other) other = self.class.create(other) - other_inv = Term.new(number: Rational(1, other.to_c)) + other_inv = Term.new(number: Rational(1, other.to_rc)) terms = {} @terms.each {|t, c| t *= other_inv @@ -99,23 +99,23 @@ if other_i<0 result = Rational(1, result) end result else - self.class.number(self.to_c ** other.to_c) + self.class.number(self.to_rc ** other.to_rc) end end def coerce(other) [self.class.create(other), self] end def ==(other) if self.class==other - self.to_c==other.to_c + self.to_rc==other.to_rc elsif Numeric===other - self.to_c==other + self.to_rc==other else super.==(other) end end @@ -159,33 +159,41 @@ to_c.imag end alias_method :imaginary, :imag def to_i - c = to_c - if c.imag.zero? - c.real.to_i + if imag.zero? + real.to_i else - raise RangeError, "can't convert %s into Integer" % c + raise RangeError, "can't convert %s into Integer" % to_c end end def to_f - c = to_c - if c.imag.zero? - c.real.to_f + if imag.zero? + real.to_f else - raise RangeError, "can't convert %s into Float" % c + raise RangeError, "can't convert %s into Float" % to_c end end + def to_rc + @cache[:to_rc] ||= @terms.map {|t, c| + nc = Complex(t.number.real.to_r, t.number.imag.to_r) + + sc = Math.sqrt(Complex(t.sqrt)) + sc = Complex(sc.real.to_r, sc.imag.to_r) + + nc * sc * c + }.sum.nonzero? || Complex(0.to_r, 0.to_r) + end + def to_r - c = to_c - if c.imag.zero? - Rational(c.real, 1) + if to_rc.imag.zero? + to_rc.real else - raise RangeError, "can't convert %s into Rational" % c + raise RangeError, "can't convert %s into Rational" % to_rc end end def expr value_to_s = -> (v) { @@ -245,17 +253,19 @@ def real? false end + def complex? + !imag.zero? + end + def integer? - c = to_c - c.imag.zero? && c.real==c.real.to_i + imag.zero? && real==real.to_i end def float? - c = to_c - c.imag.zero? && Float===c.real && c.real!=c.real.to_i + imag.zero? && Float===real && real!=real.to_i end def self.create(v) if self===v v