Class: Quadratic::Real

Inherits:
Quadratic show all
Defined in:
lib/quadratic_number/real.rb,
lib/quadratic_number.rb

Overview

Abstract class for Quadratic[d] (d > 0).

Instance Method Summary collapse

Methods inherited from Quadratic

#*, #**, #+, #-, #-@, [], #coerce, #denominator, #discriminant, #eql?, #fdiv, #hash, #initialize, #inspect, #norm, #numerator, #qconj, #quo, #trace

Constructor Details

This class inherits a constructor from Quadratic

Instance Method Details

#<=>(other) ⇒ +1/0/-1/nil

Parameters:

  • other (Object)

Returns:

  • (+1/0/-1/nil)


31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/quadratic_number/real.rb', line 31

def <=>(other)
  if other.kind_of?(Numeric)
    if other.real?
      (self - other).to_f <=> 0
    else
      n1, n2 = other.coerce(self)
      n1 <=> n2
    end
  else
    nil
  end
end

#==(other) ⇒ Boolean

Parameters:

  • other (Object)

Returns:

  • (Boolean)


48
49
50
51
52
53
54
# File 'lib/quadratic_number/real.rb', line 48

def ==(other)
  if other.kind_of?(Numeric) && other.real?
    (self - other).to_f == 0
  else
    other == self
  end
end

#rationalize(eps) ⇒ Rational

Parameters:

  • eps (Numeric)

Returns:

  • (Rational)


# File 'lib/quadratic_number/real.rb', line 87


#to_fFloat

Returns a float. Prevents cancellations of significant digits.

Examples:

-665857 + 470832 * Math.sqrt(2)        #=> -7.508788257837296e-07
Quadratic[2].new(-665857, 470832).to_f #=> -7.509119826032946e-07

Returns:

  • (Float)


71
72
73
74
75
76
77
78
79
80
# File 'lib/quadratic_number/real.rb', line 71

def to_f
  d = self.class::D
  if @a * @b < 0
    # Using #fdiv instead of #/
    # because Rational#/ returns Rational for a big Float divisor in ruby2.0
    (@a * @a - @b * @b * d).fdiv(@a - @b * Math.sqrt(d))
  else
    @a + @b * Math.sqrt(d)
  end
end

#to_iInteger

Returns:

  • (Integer)


98
99
100
101
102
# File 'lib/quadratic_number/real.rb', line 98

[:to_r, :rationalize, :to_i].each do |sym|
  define_method(sym) do |*args|
    (@b == 0 ? @a : to_f).send(sym, *args)
  end
end

#to_rRational

Returns:

  • (Rational)


# File 'lib/quadratic_number/real.rb', line 82