Class: Rational

Inherits:
Object
  • Object
show all
Defined in:
lib/long-decimal.rb

Constant Summary collapse

FLOAT_MAX_I =
Float::MAX.to_i
FLOAT_SIGNIFICANT_I =
2**56

Instance Method Summary collapse

Instance Method Details

#eql?(other) ⇒ Boolean

fix eql? for Ruby 1.8

Returns:

  • (Boolean)


2972
2973
2974
# File 'lib/long-decimal.rb', line 2972

def eql?(other)
  (other.kind_of? Rational) && self.numerator == other.numerator && self.denominator == other.denominator
end

#to_fObject

improved to_f, works better where numerator and denominator are integers beyond the range of float, but their Quotient is still expressable as Float



2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
# File 'lib/long-decimal.rb', line 2977

def to_f
  num = numerator
  den = denominator
  # puts("num=#{num} den=#{den}")
  sign = num <=> 0
  # puts("num=#{num} den=#{den} sign=#{sign}")
  if (sign.zero?)
    return 0.0
  elsif sign < 0
    num = -num
  end
  num_big = nil
  den_big = nil
  while num >= FLOAT_SIGNIFICANT_I && den >= FLOAT_SIGNIFICANT_I && (num >= FLOAT_MAX_I || den >= FLOAT_MAX_I)
    num += 0x80
    num >>= 8
    den += 0x80
    den >>= 8
  end

  if num >= FLOAT_MAX_I
    num = (num + den/2) / den
    return (sign * num).to_f
  elsif den >= FLOAT_MAX_I
    den = (den + num/2) / num
    if (den >= FLOAT_MAX_I)
      return 0.0
    else
      return sign/den.to_f
    end
  else
    return sign * (num.to_f / den.to_f)
  end
end

#to_f_origObject

retain original to_f under different name



2964
# File 'lib/long-decimal.rb', line 2964

alias :to_f_orig :to_f

#to_ld(prec = nil, mode = LongMath.standard_mode) ⇒ Object

convert self to LongDecimal. Special handling of Rational to avoid loosing information in the first step that would be needed for the second step optional first argument gives the precision for the desired result optional second argument gives the rouding mode



2954
2955
2956
2957
2958
2959
2960
2961
# File 'lib/long-decimal.rb', line 2954

def to_ld(prec = nil, mode = LongMath.standard_mode)
  if (prec.nil?)
    return LongDecimal(self)
  else
    l = LongDecimalQuot(self, prec)
    return l.round_to_scale(prec, mode)
  end
end