Class: Decimal

Inherits:
Object
  • Object
show all
Extended by:
DecimalSupport
Includes:
Comparable, AuxiliarFunctions
Defined in:
lib/decimal/decimal.rb

Overview

Decimal arbitrary precision floating point number. This implementation of Decimal is based on the Decimal module of Python, written by Eric Price, Facundo Batista, Raymond Hettinger, Aahz and Tim Peters.

Defined Under Namespace

Modules: AuxiliarFunctions Classes: Clamped, Context, ConversionSyntax, DivisionByZero, DivisionImpossible, DivisionUndefined, Error, Exception, Inexact, InvalidContext, InvalidOperation, Overflow, Rounded, Subnormal, Underflow

Constant Summary collapse

ROUND_HALF_EVEN =
:half_even
ROUND_HALF_DOWN =
:half_down
ROUND_HALF_UP =
:half_up
ROUND_FLOOR =
:floor
ROUND_CEILING =
:ceiling
ROUND_DOWN =
:down
ROUND_UP =
:up
ROUND_05UP =
:up05
EXCEPTIONS =
FlagValues(Clamped, InvalidOperation, DivisionByZero, Inexact, Overflow, Underflow,
Rounded, Subnormal, DivisionImpossible, ConversionSyntax)
DefaultContext =

the DefaultContext is the base for new contexts; it can be changed.

Decimal::Context.new(
:exact=>false, :precision=>28, :rounding=>:half_even,
:emin=> -999999999, :emax=>+999999999,
:flags=>[],
:traps=>[DivisionByZero, Overflow, InvalidOperation],
:ignored_flags=>[],
:capitals=>true,
:clamp=>true)
BasicContext =
Decimal::Context.new(DefaultContext,
:precision=>9, :rounding=>:half_up,
:traps=>[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
:flags=>[])
ExtendedContext =
Decimal::Context.new(DefaultContext,
:precision=>9, :rounding=>:half_even,
:traps=>[], :flags=>[], :clamp=>false)

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DecimalSupport

FlagValues

Methods included from AuxiliarFunctions

_convert, _dexp, _div_nearest, _dlog, _dlog10, _dpower, _iexp, _ilog, _log10_digits, _log10_lb, _nbits, _normalize, _parser, _rshift_nearest, _sqrt_nearest, dexp

Constructor Details

#initialize(*args) ⇒ Decimal

A decimal value can be defined by:

  • A String containing a text representation of the number

  • An Integer

  • A Rational

  • Another Decimal value.

  • A sign, coefficient and exponent (either as separate arguments, as an array or as a Hash with symbolic keys). This is the internal representation of Decimal, as returned by Decimal#split. The sign is +1 for plus and -1 for minus; the coefficient and exponent are integers, except for special values which are defined by :inf, :nan or :snan for the exponent.

An optional Context can be passed as the last argument to override the current context; also a hash can be passed to override specific context parameters. The Decimal() admits the same parameters and can be used as a shortcut for Decimal creation.



1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
# File 'lib/decimal/decimal.rb', line 1033

def initialize(*args)
  context = nil
  if args.size>0 && args.last.instance_of?(Context)
    context ||= args.pop
  elsif args.size>1 && args.last.instance_of?(Hash)
    context ||= args.pop
  elsif args.size==1 && args.last.instance_of?(Hash)
    arg = args.last
    args = [arg[:sign], args[:coefficient], args[:exponent]]
    arg.delete :sign
    arg.delete :coefficient
    arg.delete :exponent
    context ||= arg
  end

  context = Decimal.define_context(context)

  case args.size
  when 3
    @sign, @coeff, @exp = args
    # TO DO: validate

  when 1
    arg = args.first
    case arg

    when Decimal
      @sign, @coeff, @exp = arg.split

    when *context.coercible_types
      v = context._coerce(arg)
      @sign, @coeff, @exp = v.is_a?(Decimal) ? v.split : v

    when String
      if arg.strip != arg
        @sign,@coeff,@exp = context.exception(ConversionSyntax, "no trailing or leading whitespace is permitted").split
        return
      end
      m = _parser(arg)
      if m.nil?
        @sign,@coeff,@exp = context.exception(ConversionSyntax, "Invalid literal for Decimal: #{arg.inspect}").split
        return
      end
      @sign =  (m.sign == '-') ? -1 : +1
      if m.int || m.onlyfrac
        if m.int
          intpart = m.int
          fracpart = m.frac
        else
          intpart = ''
          fracpart = m.onlyfrac
        end
        @exp = m.exp.to_i
        if fracpart
          @coeff = (intpart+fracpart).to_i
          @exp -= fracpart.size
        else
          @coeff = intpart.to_i
        end
      else
        if m.diag
          # NaN
          @coeff = (m.diag.nil? || m.diag.empty?) ? nil : m.diag.to_i
          @coeff = nil if @coeff==0
           if @coeff
             max_diag_len = context.maximum_nan_diagnostic_digits
             if max_diag_len && @coeff >= Decimal.int_radix_power(max_diag_len)
                @sign,@coeff,@exp = context.exception(ConversionSyntax, "diagnostic info too long in NaN").split
               return
             end
           end
          @exp = m.signal ? :snan : :nan
        else
          # Infinity
          @coeff = 0
          @exp = :inf
        end
      end
    when Array
      @sign, @coeff, @exp = arg
    else
      raise TypeError, "invalid argument #{arg.inspect}"
    end
  else
    raise ArgumentError, "wrong number of arguments (#{args.size} for 1 or 3)"
  end
end

Class Attribute Details

.base_coercible_typesObject (readonly)

Returns the value of attribute base_coercible_types.



36
37
38
# File 'lib/decimal/decimal.rb', line 36

def base_coercible_types
  @base_coercible_types
end

.base_conversionsObject (readonly)

Returns the value of attribute base_conversions.



37
38
39
# File 'lib/decimal/decimal.rb', line 37

def base_conversions
  @base_conversions
end

Class Method Details

.context(*args, &blk) ⇒ Object

The current context (thread-local). If arguments are passed they are interpreted as in Decimal.define_context() to change the current context. If a block is given, this method is a synonym for Decimal.local_context().



896
897
898
899
900
901
902
903
904
905
906
907
# File 'lib/decimal/decimal.rb', line 896

def Decimal.context(*args, &blk)
  if blk
    # setup a local context
    local_context(*args, &blk)
  elsif args.empty?
    # return the current context
    Thread.current['Decimal.context'] ||= DefaultContext.dup
  else
    # change the current context
    Decimal.context = define_context(*args)
  end
end

.Context(*args) ⇒ Object

Context constructor; if an options hash is passed, the options are applied to the default context; if a Context is passed as the first argument, it is used as the base instead of the default context.

See Context#new() for the valid options



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
# File 'lib/decimal/decimal.rb', line 848

def Decimal.Context(*args)
  case args.size
    when 0
      base = DefaultContext
    when 1
      arg = args.first
      if arg.instance_of?(Context)
        base = arg
        options = nil
      elsif arg.instance_of?(Hash)
        base = DefaultContext
        options = arg
      else
        raise TypeError,"invalid argument for Decimal.Context"
      end
    when 2
      base = args.first
      options = args.last
    else
      raise ArgumentError,"wrong number of arguments (#{args.size} for 0, 1 or 2)"
  end

  if options.nil? || options.empty?
    base
  else
    Context.new(base, options)
  end

end

.context=(c) ⇒ Object

Change the current context (thread-local).



910
911
912
# File 'lib/decimal/decimal.rb', line 910

def Decimal.context=(c)
  Thread.current['Decimal.context'] = c.dup
end

.define_context(*options) ⇒ Object

Define a context by passing either of:

  • A Context object

  • A hash of options (or nothing) to alter a copy of the current context.

  • A Context object and a hash of options to alter a copy of it



882
883
884
885
886
887
888
889
890
# File 'lib/decimal/decimal.rb', line 882

def Decimal.define_context(*options)
  context = options.shift if options.first.instance_of?(Context)
  if context && options.empty?
    context
  else
    context ||= Decimal.context
    Context(context, *options)
  end
end

.Flags(*values) ⇒ Object



282
283
284
# File 'lib/decimal/decimal.rb', line 282

def self.Flags(*values)
  DecimalSupport::Flags(EXCEPTIONS,*values)
end

.infinity(sign = +1) ⇒ Object

A decimal infinite number with the specified sign



939
940
941
# File 'lib/decimal/decimal.rb', line 939

def Decimal.infinity(sign=+1)
  Decimal.new([sign, 0, :inf])
end

.int_div_radix_power(x, n) ⇒ Object

Divide by an integral power of the base: x/(radix**n) for x,n integer; returns an integer.



68
69
70
# File 'lib/decimal/decimal.rb', line 68

def self.int_div_radix_power(x,n)
  x / (10**n)
end

.int_mult_radix_power(x, n) ⇒ Object

Multiply by an integral power of the base: x*(radix**n) for x,n integer; returns an integer.



62
63
64
# File 'lib/decimal/decimal.rb', line 62

def self.int_mult_radix_power(x,n)
  x * (10**n)
end

.int_radix_power(n) ⇒ Object

Integral power of the base: radix**n for integer n; returns an integer.



56
57
58
# File 'lib/decimal/decimal.rb', line 56

def self.int_radix_power(n)
  10**n
end

.local_context(*args) ⇒ Object

Defines a scope with a local context. A context can be passed which will be set a the current context for the scope; also a hash can be passed with options to apply to the local scope. Changes done to the current context are reversed when the scope is exited.



918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/decimal/decimal.rb', line 918

def Decimal.local_context(*args)
  keep = context.dup
  Decimal.context = define_context(*args)
  result = yield Decimal.context
  # TODO: consider the convenience of copying the flags from Decimal.context to keep
  # This way a local context does not affect the settings of the previous context,
  # but flags are transferred.
  # (this could be done always or be controlled by some option)
  #   keep.flags = Decimal.context.flags
  # Another alternative to consider: logically or the flags:
  #   keep.flags ||= Decimal.context.flags # (this requires implementing || in Flags)
  Decimal.context = keep
  result
end

.nanObject

A decimal NaN (not a number)



944
945
946
# File 'lib/decimal/decimal.rb', line 944

def Decimal.nan()
  Decimal.new([+1, nil, :nan])
end

.radixObject

Numerical base of Decimal.



51
52
53
# File 'lib/decimal/decimal.rb', line 51

def self.radix
  10
end

.zero(sign = +1) ⇒ Object

A decimal number with value zero and the specified sign



934
935
936
# File 'lib/decimal/decimal.rb', line 934

def Decimal.zero(sign=+1)
  Decimal.new([sign, 0, 0])
end

Instance Method Details

#%(other, context = nil) ⇒ Object

Modulo of two decimal numbers



1263
1264
1265
# File 'lib/decimal/decimal.rb', line 1263

def %(other, context=nil)
  _bin_op :%, :modulo, other, context
end

#*(other, context = nil) ⇒ Object

Multiplication of two decimal numbers



1253
1254
1255
# File 'lib/decimal/decimal.rb', line 1253

def *(other, context=nil)
  _bin_op :*, :multiply, other, context
end

#**(other, context = nil) ⇒ Object

Power



1268
1269
1270
# File 'lib/decimal/decimal.rb', line 1268

def **(other, context=nil)
  _bin_op :**, :power, other, context
end

#+(other, context = nil) ⇒ Object

Addition of two decimal numbers



1243
1244
1245
# File 'lib/decimal/decimal.rb', line 1243

def +(other, context=nil)
  _bin_op :+, :add, other, context
end

#+@(context = nil) ⇒ Object

Unary plus operator



1237
1238
1239
1240
# File 'lib/decimal/decimal.rb', line 1237

def +@(context=nil)
  #(context || Decimal.context).plus(self)
  _pos(context)
end

#-(other, context = nil) ⇒ Object

Subtraction of two decimal numbers



1248
1249
1250
# File 'lib/decimal/decimal.rb', line 1248

def -(other, context=nil)
  _bin_op :-, :subtract, other, context
end

#-@(context = nil) ⇒ Object

Unary minus operator



1231
1232
1233
1234
# File 'lib/decimal/decimal.rb', line 1231

def -@(context=nil)
  #(context || Decimal.context).minus(self)
  _neg(context)
end

#/(other, context = nil) ⇒ Object

Division of two decimal numbers



1258
1259
1260
# File 'lib/decimal/decimal.rb', line 1258

def /(other, context=nil)
  _bin_op :/, :divide, other, context
end

#<=>(other) ⇒ Object

Internal comparison operator: returns -1 if the first number is less than the second, 0 if both are equal or +1 if the first is greater than the secong.



2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
# File 'lib/decimal/decimal.rb', line 2007

def <=>(other)
  case other
  when *Decimal.context.coercible_types_or_decimal
    other = Decimal(other)
    if self.special? || other.special?
      if self.nan? || other.nan?
        1
      else
        self_v = self.finite? ? 0 : self.sign
        other_v = other.finite? ? 0 : other.sign
        self_v <=> other_v
      end
    else
      if self.zero?
        if other.zero?
          0
        else
          -other.sign
        end
      elsif other.zero?
        self.sign
      elsif other.sign < self.sign
        +1
      elsif self.sign < other.sign
        -1
      else
        self_adjusted = self.adjusted_exponent
        other_adjusted = other.adjusted_exponent
        if self_adjusted == other_adjusted
          self_padded,other_padded = self.integral_significand,other.integral_significand
          d = self.integral_exponent - other.integral_exponent
          if d>0
            self_padded *= Decimal.int_radix_power(d)
          else
            other_padded *= Decimal.int_radix_power(-d)
          end
          (self_padded <=> other_padded)*self.sign
        elsif self_adjusted > other_adjusted
          self.sign
        else
          -self.sign
        end
      end
    end
  else
    if defined? other.coerce
      x, y = other.coerce(self)
      x <=> y
    else
      nil
    end
  end
end

#==(other) ⇒ Object



2060
2061
2062
# File 'lib/decimal/decimal.rb', line 2060

def ==(other)
  (self<=>other) == 0
end

#_abs(round = true, context = nil) ⇒ Object

Returns a copy with positive sign



2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
# File 'lib/decimal/decimal.rb', line 2877

def _abs(round=true, context=nil)
  return copy_abs if not round

  if special?
    ans = _check_nans(context)
    return ans if ans
  end
  if sign>0
    ans = _neg(context)
  else
    ans = _pos(context)
  end
  ans
end

#_check_nans(context = nil, other = nil) ⇒ Object

Check if the number or other is NaN, signal if sNaN or return NaN; return nil if none is NaN.



2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
# File 'lib/decimal/decimal.rb', line 2774

def _check_nans(context=nil, other=nil)
  #self_is_nan = self.nan?
  #other_is_nan = other.nil? ? false : other.nan?
  if self.nan? || (other && other.nan?)
    context = Decimal.define_context(context)
    return context.exception(InvalidOperation, 'sNaN', self) if self.snan?
    return context.exception(InvalidOperation, 'sNaN', other) if other && other.snan?
    return self._fix_nan(context) if self.nan?
    return other._fix_nan(context)
  else
    return nil
  end
end

#_fix(context) ⇒ Object

Round if it is necessary to keep within precision.



2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
# File 'lib/decimal/decimal.rb', line 2893

def _fix(context)
  return self if context.exact?

  if special?
    if nan?
      return _fix_nan(context)
    else
      return Decimal.new(self)
    end
  end

  etiny = context.etiny
  etop  = context.etop
  if zero?
    exp_max = context.clamp? ? etop : context.emax
    new_exp = [[@exp, etiny].max, exp_max].min
    if new_exp!=@exp
      context.exception Clamped
      return Decimal.new([sign,0,new_exp])
    else
      return Decimal.new(self)
    end
  end

  nd = number_of_digits
  exp_min = nd + @exp - context.precision
  if exp_min > etop
    context.exception Inexact
    context.exception Rounded
    return context.exception(Overflow, 'above Emax', sign)
  end

  self_is_subnormal = exp_min < etiny

  if self_is_subnormal
    context.exception Subnormal
    exp_min = etiny
  end

  if @exp < exp_min
    context.exception Rounded
    # dig is the digits number from 0 (MS) to number_of_digits-1 (LS)
    # dg = numberof_digits-dig is from 1 (LS) to number_of_digits (MS)
    dg = exp_min - @exp # dig = number_of_digits + exp - exp_min
    if dg > number_of_digits # dig<0
      d = Decimal.new([sign,1,exp_min-1])
      dg = number_of_digits # dig = 0
    else
      d = Decimal.new(self)
    end
    changed = d._round(context.rounding, dg)
    coeff = Decimal.int_div_radix_power(d.integral_significand, dg)
    coeff += 1 if changed==1
    ans = Decimal.new([sign, coeff, exp_min])
    if changed!=0
      context.exception Inexact
      if self_is_subnormal
        context.exception Underflow
        if ans.zero?
          context.exception Clamped
        end
      elsif ans.number_of_digits == context.precision+1
        if ans.integral_exponent< etop
          ans = Decimal.new([ans.sign, Decimal.int_div_radix_power(ans.integral_significand,1), ans.integral_exponent+1])
        else
          ans = context.exception(Overflow, 'above Emax', d.sign)
        end
      end
    end
    return ans
  end

  if context.clamp? &&  @exp>etop
    context.exception Clamped
    self_padded = Decimal.int_mult_radix_power(@coeff, @exp-etop)
    return Decimal.new([sign,self_padded,etop])
  end

  return Decimal.new(self)

end

#_fix_nan(context) ⇒ Object

adjust payload of a NaN to the context



2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
# File 'lib/decimal/decimal.rb', line 2976

def _fix_nan(context)
  if  !context.exact?
    payload = @coeff
    payload = nil if payload==0

    max_payload_len = context.maximum_nan_diagnostic_digits

    if number_of_digits > max_payload_len
        payload = payload.to_s[-max_payload_len..-1].to_i
        return Decimal([@sign, payload, @exp])
    end
  end
  Decimal(self)
end

#_neg(context = nil) ⇒ Object

Returns copy with sign inverted



2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
# File 'lib/decimal/decimal.rb', line 2847

def _neg(context=nil)
  if special?
    ans = _check_nans(context)
    return ans if ans
  end
  if zero?
    ans = copy_abs
  else
    ans = copy_negate
  end
  context = Decimal.define_context(context)
  ans._fix(context)
end

#_pos(context = nil) ⇒ Object

Returns a copy with precision adjusted



2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
# File 'lib/decimal/decimal.rb', line 2862

def _pos(context=nil)
  if special?
    ans = _check_nans(context)
    return ans if ans
  end
  if zero?
    ans = copy_abs
  else
    ans = Decimal.new(self)
  end
  context = Decimal.define_context(context)
  ans._fix(context)
end

#_rescale(exp, rounding) ⇒ Object

Rescale so that the exponent is exp, either by padding with zeros or by truncating digits, using the given rounding mode.

Specials are returned without change. This operation is quiet: it raises no flags, and uses no information from the context.

exp = exp to scale to (an integer) rounding = rounding mode



2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
# File 'lib/decimal/decimal.rb', line 2797

def _rescale(exp, rounding)

  return Decimal.new(self) if special?
  return Decimal.new([sign, 0, exp]) if zero?
  return Decimal.new([sign, @coeff*Decimal.int_radix_power(self.integral_exponent - exp), exp]) if self.integral_exponent > exp
  #nd = number_of_digits + self.integral_exponent - exp
  nd = exp - self.integral_exponent
  if number_of_digits < nd
    slf = Decimal.new([sign, 1, exp-1])
    nd = number_of_digits
  else
    slf = Decimal.new(self)
  end
  changed = slf._round(rounding, nd)
  coeff = Decimal.int_div_radix_power(@coeff, nd)
  coeff += 1 if changed==1
  Decimal.new([slf.sign, coeff, exp])

end

#_watched_rescale(exp, context, watch_exp) ⇒ Object



2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
# File 'lib/decimal/decimal.rb', line 2817

def _watched_rescale(exp, context, watch_exp)
  if !watch_exp
    ans = _rescale(exp, context.rounding)
    context.exception(Rounded) if ans.integral_exponent > self.integral_exponent
    context.exception(Inexact) if ans != self
    return ans
  end

  if exp < context.etiny || exp > context.emax
    return context.exception(InvalidOperation, "target operation out of bounds in quantize/rescale")
  end

  return Decimal.new([@sign, 0, exp])._fix(context) if zero?

  self_adjusted = adjusted_exponent
  return context.exception(InvalidOperation,"exponent of quantize/rescale result too large for current context") if self_adjusted > context.emax
  return context.exception(InvalidOperation,"quantize/rescale has too many digits for current context") if (self_adjusted - exp + 1 > context.precision) && !context.exact?

  ans = _rescale(exp, context.rounding)
  return context.exception(InvalidOperation,"exponent of rescale result too large for current context") if ans.adjusted_exponent > context.emax
  return context.exception(InvalidOperation,"rescale result has too many digits for current context") if (ans.number_of_digits > context.precision) && !context.exact?
  if ans.integral_exponent > self.integral_exponent
    context.exception(Rounded)
    context.exception(Inexact) if ans!=self
  end
  context.exception(Subnormal) if !ans.zero? && (ans.adjusted_exponent < context.emin)
  return ans._fix(context)
end

#abs(context = nil) ⇒ Object

Absolute value



1434
1435
1436
1437
1438
1439
1440
# File 'lib/decimal/decimal.rb', line 1434

def abs(context=nil)
  if special?
    ans = _check_nans(context)
    return ans if ans
  end
  sign<0 ? _neg(context) : _pos(context)
end

#add(other, context = nil) ⇒ Object

Addition



1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
# File 'lib/decimal/decimal.rb', line 1273

def add(other, context=nil)

  context = Decimal.define_context(context)
  other = _convert(other)

  if self.special? || other.special?
    ans = _check_nans(context,other)
    return ans if ans

    if self.infinite?
      if self.sign != other.sign && other.infinite?
        return context.exception(InvalidOperation, '-INF + INF')
      end
      return Decimal(self)
    end

    return Decimal(other) if other.infinite?
  end

  exp = [self.integral_exponent, other.integral_exponent].min
  negativezero = (context.rounding == ROUND_FLOOR && self.sign != other.sign)

  if self.zero? && other.zero?
    sign = [self.sign, other.sign].max
    sign = -1 if negativezero
    ans = Decimal.new([sign, 0, exp])._fix(context)
    return ans
  end

  if self.zero?
    exp = [exp, other.integral_exponent - context.precision - 1].max unless context.exact?
    return other._rescale(exp, context.rounding)._fix(context)
  end

  if other.zero?
    exp = [exp, self.integral_exponent - context.precision - 1].max unless context.exact?
    return self._rescale(exp, context.rounding)._fix(context)
  end

  op1, op2 = _normalize(self, other, context.precision)

  result_sign = result_coeff = result_exp = nil
  if op1.sign != op2.sign
    return ans = Decimal.new([negativezero ? -1 : +1, 0, exp])._fix(context) if op1.integral_significand == op2.integral_significand
    op1,op2 = op2,op1 if op1.integral_significand < op2.integral_significand
    result_sign = op1.sign
    op1,op2 = op1.copy_negate, op2.copy_negate if result_sign < 0
  elsif op1.sign < 0
    result_sign = -1
    op1,op2 = op1.copy_negate, op2.copy_negate
  else
    result_sign = +1
  end

  if op2.sign == +1
    result_coeff = op1.integral_significand + op2.integral_significand
  else
    result_coeff = op1.integral_significand - op2.integral_significand
  end

  result_exp = op1.integral_exponent

  return Decimal([result_sign, result_coeff, result_exp])._fix(context)

end

#adjusted_exponentObject

Exponent of the magnitude of the most significant digit of the operand



2094
2095
2096
2097
2098
2099
2100
# File 'lib/decimal/decimal.rb', line 2094

def adjusted_exponent
  if special?
    0
  else
    @exp + number_of_digits - 1
  end
end

#ceil(opt = {}) ⇒ Object

General ceiling operation (as for Float) with same options for precision as Decimal#round()



2354
2355
2356
2357
# File 'lib/decimal/decimal.rb', line 2354

def ceil(opt={})
  opt[:rounding] = :ceiling
  round opt
end

#coerce(other) ⇒ Object

Used internally to convert numbers to be used in an operation to a suitable numeric type



1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/decimal/decimal.rb', line 1208

def coerce(other)
  case other
    when *Decimal.context.coercible_types_or_decimal
      [Decimal(other),self]
    else
      super
  end
end

#compare(other, context = nil) ⇒ Object

Compares like <=> but returns a Decimal value.



2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
# File 'lib/decimal/decimal.rb', line 2075

def compare(other, context=nil)

  other = _convert(other)

  if self.special? || other.special?
    ans = _check_nans(context, other)
    return ans if ans
  end

  return Decimal(self <=> other)

end

#convert_to(type, context = nil) ⇒ Object

Convert to other numerical type.



1897
1898
1899
1900
# File 'lib/decimal/decimal.rb', line 1897

def convert_to(type, context=nil)
  context = Decimal.define_context(context)
  context.convert_to(type, self)
end

#copy_absObject

Returns a copy of with the sign set to +



2144
2145
2146
# File 'lib/decimal/decimal.rb', line 2144

def copy_abs
  Decimal.new([+1,@coeff,@exp])
end

#copy_negateObject

Returns a copy of with the sign inverted



2149
2150
2151
# File 'lib/decimal/decimal.rb', line 2149

def copy_negate
  Decimal.new([-@sign,@coeff,@exp])
end

#copy_sign(other) ⇒ Object

Returns a copy of with the sign of other



2154
2155
2156
# File 'lib/decimal/decimal.rb', line 2154

def copy_sign(other)
  Decimal.new([other.sign, @coeff, @exp])
end

#digitsObject

Digits of the significand as an array of integers



2089
2090
2091
# File 'lib/decimal/decimal.rb', line 2089

def digits
  @coeff.to_s.split('').map{|d| d.to_i}
end

#div(other, context = nil) ⇒ Object

Ruby-style integer division: (x/y).floor



1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
# File 'lib/decimal/decimal.rb', line 1701

def div(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return [ans,ans] if ans

  sign = self.sign * other.sign

  if self.infinite?
    return context.exception(InvalidOperation, 'INF // INF') if other.infinite?
    return Decimal.infinity(sign)
  end

  if other.zero?
    if self.zero?
      return context.exception(DivisionUndefined, '0 // 0')
    else
      return context.exception(DivisionByZero, 'x // 0', sign)
    end
  end
  return self._divide_floor(other, context).first
end

#divide(other, context = nil) ⇒ Object

Division



1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
# File 'lib/decimal/decimal.rb', line 1383

def divide(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)
  resultsign = self.sign * other.sign
  if self.special? || other.special?
    ans = _check_nans(context,other)
    return ans if ans
    if self.infinite?
      return context.exception(InvalidOperation,"(+-)INF/(+-)INF") if other.infinite?
      return Decimal.infinity(resultsign)
    end
    if other.infinite?
      context.exception(Clamped,"Division by infinity")
      return Decimal.new([resultsign, 0, context.etiny])
    end
  end

  if other.zero?
    return context.exception(DivisionUndefined, '0 / 0') if self.zero?
    return context.exception(DivisionByZero, 'x / 0', resultsign)
  end

  if self.zero?
    exp = self.integral_exponent - other.integral_exponent
    coeff = 0
  else
    prec = context.exact? ? self.number_of_digits + 4*other.number_of_digits : context.precision # this assumes radix==10
    shift = other.number_of_digits - self.number_of_digits + prec + 1
    exp = self.integral_exponent - other.integral_exponent - shift
    if shift >= 0
      coeff, remainder = (self.integral_significand*Decimal.int_radix_power(shift)).divmod(other.integral_significand)
    else
      coeff, remainder = self.integral_significand.divmod(other.integral_significand*Decimal.int_radix_power(-shift))
    end
    if remainder != 0
      return context.exception(Inexact) if context.exact?
      coeff += 1 if (coeff%(Decimal.radix/2)) == 0
    else
      ideal_exp = self.integral_exponent - other.integral_exponent
      while (exp < ideal_exp) && ((coeff % Decimal.radix)==0)
        coeff /= Decimal.radix
        exp += 1
      end
    end

  end
  return Decimal([resultsign, coeff, exp])._fix(context)

end

#divide_int(other, context = nil) ⇒ Object

General Decimal Arithmetic Specification integer division: (x/y).truncate



1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
# File 'lib/decimal/decimal.rb', line 1676

def divide_int(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return ans if ans

  sign = self.sign * other.sign

  if self.infinite?
    return context.exception(InvalidOperation, 'INF // INF') if other.infinite?
    return Decimal.infinity(sign)
  end

  if other.zero?
    if self.zero?
      return context.exception(DivisionUndefined, '0 // 0')
    else
      return context.exception(DivisionByZero, 'x // 0', sign)
    end
  end
  return self._divide_truncate(other, context).first
end

#divmod(other, context = nil) ⇒ Object

Ruby-style integer division and modulo: (x/y).floor, x - y*(x/y).floor



1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
# File 'lib/decimal/decimal.rb', line 1642

def divmod(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return [ans,ans] if ans

  sign = self.sign * other.sign

  if self.infinite?
    if other.infinite?
      ans = context.exception(InvalidOperation, 'divmod(INF,INF)')
      return [ans,ans]
    else
      return [Decimal.infinity(sign), context.exception(InvalidOperation, 'INF % x')]
    end
  end

  if other.zero?
    if self.zero?
      ans = context.exception(DivisionUndefined, 'divmod(0,0)')
      return [ans,ans]
    else
      return [context.exception(DivisionByZero, 'x // 0', sign),
               context.exception(InvalidOperation, 'x % 0')]
    end
  end

  quotient, remainder = self._divide_floor(other, context)
  return [quotient, remainder._fix(context)]
end

#divrem(other, context = nil) ⇒ Object

General Decimal Arithmetic Specification integer division and remainder:

(x/y).truncate, x - y*(x/y).truncate


1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
# File 'lib/decimal/decimal.rb', line 1609

def divrem(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return [ans,ans] if ans

  sign = self.sign * other.sign

  if self.infinite?
    if other.infinite?
      ans = context.exception(InvalidOperation, 'divmod(INF,INF)')
      return [ans,ans]
    else
      return [Decimal.infinity(sign), context.exception(InvalidOperation, 'INF % x')]
    end
  end

  if other.zero?
    if self.zero?
      ans = context.exception(DivisionUndefined, 'divmod(0,0)')
      return [ans,ans]
    else
      return [context.exception(DivisionByZero, 'x // 0', sign),
               context.exception(InvalidOperation, 'x % 0')]
    end
  end

  quotient, remainder = self._divide_truncate(other, context)
  return [quotient, remainder._fix(context)]
end

#eql?(other) ⇒ Boolean

Returns:



2069
2070
2071
2072
# File 'lib/decimal/decimal.rb', line 2069

def eql?(other)
  return false unless other.is_a?(Decimal)
  reduce.split == other.reduce.split
end

#even?Boolean

returns true if is an even integer

Returns:



2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
# File 'lib/decimal/decimal.rb', line 2177

def even?
  # integral? && ((to_i%2)==0)
  if finite?
    if @exp>0 || @coeff==0
      true
    else
      if @exp <= -number_of_digits
        false
      else
        m = Decimal.int_radix_power(-@exp)
        if (@coeff % m) == 0
          # ((@coeff / m) % 2) == 0
          ((@coeff / m) & 1) == 0
        else
          false
        end
      end
    end
  else
    false
  end
end

#exp(context = nil) ⇒ Object

Exponential function



2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
# File 'lib/decimal/decimal.rb', line 2654

def exp(context=nil)
  context = Decimal.define_context(context)

  # exp(NaN) = NaN
  ans = _check_nans(context)
  return ans if ans

  # exp(-Infinity) = 0
  return Decimal.zero if self.infinite? && (self.sign == -1)

  # exp(0) = 1
  return Decimal(1) if self.zero?

  # exp(Infinity) = Infinity
  return Decimal(self) if self.infinite?

  # the result is now guaranteed to be inexact (the true
  # mathematical result is transcendental). There's no need to
  # raise Rounded and Inexact here---they'll always be raised as
  # a result of the call to _fix.
  return context.exception(Inexact, 'Inexact exp') if context.exact?
  p = context.precision
  adj = self.adjusted_exponent

  # we only need to do any computation for quite a small range
  # of adjusted exponents---for example, -29 <= adj <= 10 for
  # the default context.  For smaller exponent the result is
  # indistinguishable from 1 at the given precision, while for
  # larger exponent the result either overflows or underflows.
  if self.sign == +1 and adj > ((context.emax+1)*3).to_s.length
    # overflow
    ans = Decimal(+1, 1, context.emax+1)
  elsif self.sign == -1 and adj > ((-context.etiny+1)*3).to_s.length
    # underflow to 0
    ans = Decimal(+1, 1, context.etiny-1)
  elsif self.sign == +1 and adj < -p
    # p+1 digits; final round will raise correct flags
    ans = Decimal(+1, Decimal.int_radix_power(p)+1, -p)
  elsif self.sign == -1 and adj < -p-1
    # p+1 digits; final round will raise correct flags
    ans = Decimal(+1, Decimal.int_radix_power(p+1)-1, -p-1)
  else
    # general case
    c = self.integral_significand
    e = self.integral_exponent
    c = -c if self.sign == -1

    # compute correctly rounded result: increase precision by
    # 3 digits at a time until we get an unambiguously
    # roundable result
    extra = 3
    coeff = exp = nil
    loop do
      coeff, exp = _dexp(c, e, p+extra)
      break if (coeff % (5*10**(coeff.to_s.length-p-1)))!=0
      extra += 3
    end
    ans = Decimal(+1, coeff, exp)
  end

  # at this stage, ans should round correctly with *any*
  # rounding mode, not just with ROUND_HALF_EVEN
  Decimal.context(context, :rounding=>:half_even) do |local_context|
    ans = ans._fix(local_context)
    context.flags = local_context.flags
  end

  return ans
end

#finite?Boolean

Returns whether the number is finite

Returns:



1156
1157
1158
# File 'lib/decimal/decimal.rb', line 1156

def finite?
  !special?
end

#floor(opt = {}) ⇒ Object

General floor operation (as for Float) with same options for precision as Decimal#round()



2361
2362
2363
2364
# File 'lib/decimal/decimal.rb', line 2361

def floor(opt={})
  opt[:rounding] = :floor
  round opt
end

#fma(other, third, context = nil) ⇒ Object

Fused multiply-add.

Computes (self*other+third) with no rounding of the intermediate product self*other.



2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
# File 'lib/decimal/decimal.rb', line 2376

def fma(other, third, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)
  third = _convert(third)
  if self.special? || other.special?
    return context.exception(InvalidOperation, 'sNaN', self) if self.snan?
    return context.exception(InvalidOperation, 'sNaN', other) if other.snan?
    if self.nan?
      product = self
    elsif other.nan?
      product = other
    elsif self.infinite?
      return context.exception(InvalidOperation, 'INF * 0 in fma') if other.zero?
      product = Decimal.infinity(self.sign*other.sign)
    elsif other.infinite?
      return context.exception(InvalidOperation, '0 * INF  in fma') if self.zero?
      product = Decimal.infinity(self.sign*other.sign)
    end
  else
    product = Decimal.new([self.sign*other.sign,self.integral_significand*other.integral_significand, self.integral_exponent+other.integral_exponent])
  end
  return product.add(third, context)
end

#fractional_exponentObject

Exponent as though the significand were a fraction (the decimal point before its first digit)



2108
2109
2110
# File 'lib/decimal/decimal.rb', line 2108

def fractional_exponent
  scientific_exponent + 1
end

#hashObject



2065
2066
2067
# File 'lib/decimal/decimal.rb', line 2065

def hash
  ([Decimal]+reduce.split).hash # TODO: optimize
end

#infinite?Boolean

Returns whether the number is infinite

Returns:



1151
1152
1153
# File 'lib/decimal/decimal.rb', line 1151

def infinite?
  @exp == :inf
end

#inspectObject



1999
2000
2001
2002
2003
# File 'lib/decimal/decimal.rb', line 1999

def inspect
  #"Decimal('#{self}')"
  #debug:
  "Decimal('#{self}') [coeff:#{@coeff.inspect} exp:#{@exp.inspect} s:#{@sign.inspect}]"
end

#integral?Boolean

Returns true if the value is an integer

Returns:



2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
# File 'lib/decimal/decimal.rb', line 2159

def integral?
  if finite?
    if @exp>=0 || @coeff==0
      true
    else
      if @exp <= -number_of_digits
        false
      else
        m = Decimal.int_radix_power(-@exp)
        (@coeff % m) == 0
      end
    end
  else
    false
  end
end

#integral_exponentObject

Exponent of the significand as an integer



2124
2125
2126
2127
# File 'lib/decimal/decimal.rb', line 2124

def integral_exponent
  # fractional_exponent - number_of_digits
  @exp
end

#integral_significandObject

Significand as an integer, unsigned



2119
2120
2121
# File 'lib/decimal/decimal.rb', line 2119

def integral_significand
  @coeff
end

#ln(context = nil) ⇒ Object

Returns the natural (base e) logarithm



2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
# File 'lib/decimal/decimal.rb', line 2725

def ln(context=nil)
  context = Decimal.define_context(context)

  # ln(NaN) = NaN
  ans = _check_nans(context)
  return ans if ans

  # ln(0.0) == -Infinity
  return Decimal.infinity(-1) if self.zero?

  # ln(Infinity) = Infinity
  return Decimal.infinity if self.infinite? && self.sign == +1

  # ln(1.0) == 0.0
  return Decimal.zero if self == Decimal(1)

  # ln(negative) raises InvalidOperation
  return context.exception(InvalidOperation, 'ln of a negative value') if self.sign==-1

  # result is irrational, so necessarily inexact
  return context.exception(Inexact, 'Inexact exp') if context.exact?

  c = self.integral_significand
  e = self.integral_exponent
  p = context.precision

  # correctly rounded result: repeatedly increase precision by 3
  # until we get an unambiguously roundable result
  places = p - self._ln_exp_bound + 2 # at least p+3 places
  coeff = nil
  loop do
    coeff = _dlog(c, e, places)
    # assert coeff.to_s.length-p >= 1
    break if (coeff % (5*10**(coeff.abs.to_s.length-p-1))) != 0
    places += 3
  end
  ans = Decimal((coeff<0) ? -1 : +1, coeff.abs, -places)

  Decimal.context(context, :rounding=>:half_even) do |local_context|
    ans = ans._fix(local_context)
    context.flags = local_context.flags
  end
  return ans
end

#log10(context = nil) ⇒ Object

Returns the base 10 logarithm



2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
# File 'lib/decimal/decimal.rb', line 2604

def log10(context=nil)
  context = Decimal.define_context(context)

  # log10(NaN) = NaN
  ans = _check_nans(context)
  return ans if ans

  # log10(0.0) == -Infinity
  return Decimal.infinity(-1) if self.zero?

  # log10(Infinity) = Infinity
  return Decimal.infinity if self.infinite? && self.sign == +1

  # log10(negative or -Infinity) raises InvalidOperation
  return context.exception(InvalidOperation, 'log10 of a negative value') if self.sign == -1

  digits = self.digits
  # log10(10**n) = n
  if digits.first == 1 && digits[1..-1].all?{|d| d==0}
    # answer may need rounding
    ans = Decimal(self.integral_exponent + digits.size - 1)
    return ans if context.exact?
  else
    # result is irrational, so necessarily inexact
    return context.exception(Inexact, "Inexact power") if context.exact?
    c = self.integral_significand
    e = self.integral_exponent
    p = context.precision

    # correctly rounded result: repeatedly increase precision
    # until result is unambiguously roundable
    places = p-self._log10_exp_bound+2
    coeff = nil
    loop do
      coeff = _dlog10(c, e, places)
      # assert coeff.abs.to_s.length-p >= 1
      break if (coeff % (5*10**(coeff.abs.to_s.length-p-1)))!=0
      places += 3
    end
    ans = Decimal(coeff<0 ? -1 : +1, coeff.abs, -places)
  end

  Decimal.context(context, :rounding=>:half_even) do |local_context|
    ans = ans._fix(local_context)
    context.flags = local_context.flags
  end
  return ans
end

#logb(context = nil) ⇒ Object

Returns the exponent of the magnitude of the most significant digit.

The result is the integer which is the exponent of the magnitude of the most significant digit of the number (as though it were truncated to a single digit while maintaining the value of that digit and without limiting the resulting exponent).



1868
1869
1870
1871
1872
1873
1874
1875
# File 'lib/decimal/decimal.rb', line 1868

def logb(context=nil)
  context = Decimal.define_context(context)
  ans = _check_nans(context)
  return ans if ans
  return Decimal.infinity if infinite?
  return context.exception(DivisionByZero,'logb(0)',-1) if zero?
  Decimal.new(adjusted_exponent)
end

#minus(context = nil) ⇒ Object

Unary prefix minus operator



1448
1449
1450
# File 'lib/decimal/decimal.rb', line 1448

def minus(context=nil)
  _neg(context)
end

#modulo(other, context = nil) ⇒ Object

Ruby-style modulo: x - y*div(x,y)



1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
# File 'lib/decimal/decimal.rb', line 1727

def modulo(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return ans if ans

  #sign = self.sign * other.sign

  if self.infinite?
    return context.exception(InvalidOperation, 'INF % x')
  elsif other.zero?
    if self.zero?
      return context.exception(DivisionUndefined, '0 % 0')
    else
      return context.exception(InvalidOperation, 'x % 0')
    end
  end

  return self._divide_floor(other, context).last._fix(context)
end

#multiply(other, context = nil) ⇒ Object

Multiplication



1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
# File 'lib/decimal/decimal.rb', line 1354

def multiply(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)
  resultsign = self.sign * other.sign
  if self.special? || other.special?
    ans = _check_nans(context,other)
    return ans if ans

    if self.infinite?
      return context.exception(InvalidOperation,"(+-)INF * 0") if other.zero?
      return Decimal.infinity(resultsign)
    end
    if other.infinite?
      return context.exception(InvalidOperation,"0 * (+-)INF") if self.zero?
      return Decimal.infinity(resultsign)
    end
  end

  resultexp = self.integral_exponent + other.integral_exponent

  return Decimal([resultsign, 0, resultexp])._fix(context) if self.zero? || other.zero?
  #return Decimal([resultsign, other.integral_significand, resultexp])._fix(context) if self.integral_significand==1
  #return Decimal([resultsign, self.integral_significand, resultexp])._fix(context) if other.integral_significand==1

  return Decimal([resultsign, other.integral_significand*self.integral_significand, resultexp])._fix(context)

end

#nan?Boolean

Returns whether the number is not actualy one (NaN, not a number).

Returns:



1136
1137
1138
# File 'lib/decimal/decimal.rb', line 1136

def nan?
  @exp==:nan || @exp==:snan
end

#next_minus(context = nil) ⇒ Object

Largest representable number smaller than itself



1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'lib/decimal/decimal.rb', line 1453

def next_minus(context=nil)
  context = Decimal.define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    if infinite?
      return Decimal.new(self) if @sign == -1
      # @sign == +1
      if context.exact?
         return context.exception(InvalidOperation, 'Exact +INF next minus')
      else
        return Decimal.new(+1, context.maximum_significand, context.etop)
      end
    end
  end

  return context.exception(InvalidOperation, 'Exact next minus') if context.exact?

  result = nil
  Decimal.local_context(context) do |local|
    local.rounding = :floor
    local.ignore_all_flags
    result = self._fix(local)
    if result == self
      result = self - Decimal(+1, 1, local.etiny-1)
    end
  end
  result
end

#next_plus(context = nil) ⇒ Object

Smallest representable number larger than itself



1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
# File 'lib/decimal/decimal.rb', line 1484

def next_plus(context=nil)
  context = Decimal.define_context(context)

  if special?
    ans = _check_nans(context)
    return ans if ans
    if infinite?
      return Decimal.new(self) if @sign == +1
      # @sign == -1
      if context.exact?
         return context.exception(InvalidOperation, 'Exact -INF next plus')
      else
        return Decimal.new(-1, context.maximum_significand, context.etop)
      end
    end
  end

  return context.exception(InvalidOperation, 'Exact next plus') if context.exact?

  result = nil
  Decimal.local_context(context) do |local|
    local.rounding = :ceiling
    local.ignore_all_flags
    result = self._fix(local)
    if result == self
      result = self + Decimal(+1, 1, local.etiny-1)
    end
  end
  result

end

#next_toward(other, context = nil) ⇒ Object

Returns the number closest to self, in the direction towards other.



1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
# File 'lib/decimal/decimal.rb', line 1517

def next_toward(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)
  ans = _check_nans(context,other)
  return ans if ans

  return context.exception(InvalidOperation, 'Exact next_toward') if context.exact?

  comparison = self <=> other
  return self.copy_sign(other) if comparison == 0

  if comparison == -1
    result = self.next_plus(context)
  else # comparison == 1
    result = self.next_minus(context)
  end

  # decide which flags to raise using value of ans
  if result.infinite?
    context.exception Overflow, 'Infinite result from next_toward', result.sign
    context.exception Rounded
    context.exception Inexact
  elsif result.adjusted_exponent < context.emin
    context.exception Underflow
    context.exception Subnormal
    context.exception Rounded
    context.exception Inexact
    # if precision == 1 then we don't raise Clamped for a
    # result 0E-etiny.
    context.exception Clamped if result.zero?
  end

  result
end

#nonzero?Boolean

Returns whether the number not zero

Returns:



1166
1167
1168
# File 'lib/decimal/decimal.rb', line 1166

def nonzero?
  special? || @coeff>0
end

#normal?(context = nil) ⇒ Boolean

Returns whether the number is normal

Returns:



1178
1179
1180
1181
1182
# File 'lib/decimal/decimal.rb', line 1178

def normal?(context=nil)
  return true if special? || zero?
  context = Decimal.define_context(context)
  (context.emin <= self.adjusted_exponent) &&  (self.adjusted_exponent <= context.emax)
end

#number_class(context = nil) ⇒ Object

Classifies a number as one of ‘sNaN’, ‘NaN’, ‘-Infinity’, ‘-Normal’, ‘-Subnormal’, ‘-Zero’,

'+Zero', '+Subnormal', '+Normal', '+Infinity'


1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
# File 'lib/decimal/decimal.rb', line 1187

def number_class(context=nil)
  return "sNaN" if snan?
  return "NaN" if nan?
  if infinite?
    return '+Infinity' if @sign==+1
    return '-Infinity' # if @sign==-1
  end
  if zero?
    return '+Zero' if @sign==+1
    return '-Zero' # if @sign==-1
  end
  context = Decimal.define_context(context)
  if subnormal?(context)
    return '+Subnormal' if @sign==+1
    return '-Subnormal' # if @sign==-1
  end
  return '+Normal' if @sign==+1
  return '-Normal' if @sign==-1
end

#number_of_digitsObject

Number of digits in the significand



2113
2114
2115
2116
# File 'lib/decimal/decimal.rb', line 2113

def number_of_digits
  # digits.size
  @coeff.to_s.size
end

#odd?Boolean

returns true if is an odd integer

Returns:



2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
# File 'lib/decimal/decimal.rb', line 2201

def odd?
  # integral? && ((to_i%2)==1)
  # integral? && !even?
  if finite?
    if @exp>0 || @coeff==0
      false
    else
      if @exp <= -number_of_digits
        false
      else
        m = Decimal.int_radix_power(-@exp)
        if (@coeff % m) == 0
          # ((@coeff / m) % 2) == 1
          ((@coeff / m) & 1) == 1
        else
          false
        end
      end
    end
  else
    false
  end
end

#plus(context = nil) ⇒ Object

Unary prefix plus operator



1443
1444
1445
# File 'lib/decimal/decimal.rb', line 1443

def plus(context=nil)
  _pos(context)
end

#power(other, modulo = nil, context = nil) ⇒ Object

Raises to the power of x, to modulo if given.

With two arguments, compute self**other. If self is negative then other must be integral. The result will be inexact unless other is integral and the result is finite and can be expressed exactly in ‘precision’ digits.

With three arguments, compute (self**other) % modulo. For the three argument form, the following restrictions on the arguments hold:

- all three arguments must be integral
- other must be nonnegative
- at least one of self or other must be nonzero
- modulo must be nonzero and have at most 'precision' digits

The result of a.power(b, modulo) is identical to the result that would be obtained by computing (a**b) % modulo with unbounded precision, but is computed more efficiently. It is always exact.



2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
# File 'lib/decimal/decimal.rb', line 2420

def power(other, modulo=nil, context=nil)

  if context.nil? && (modulo.is_a?(Context) || modulo.is_a?(Hash))
    context = modulo
    modulo = nil
  end

  return self.power_modulo(other, modulo, context) if modulo

  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context, other)
  return ans if ans

  # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
  if other.zero?
    if self.zero?
      return context.exception(InvalidOperation, '0 ** 0')
    else
      return Decimal(1)
    end
  end

  # result has sign -1 iff self.sign is -1 and other is an odd integer
  result_sign = +1
  _self = self
  if _self.sign == -1
    if other.integral?
      result_sign = -1 if !other.even?
    else
      # -ve**noninteger = NaN
      # (-0)**noninteger = 0**noninteger
      unless self.zero?
        return context.exception(InvalidOperation, 'x ** y with x negative and y not an integer')
      end
    end
    # negate self, without doing any unwanted rounding
    _self = self.copy_negate
  end

  # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
  if _self.zero?
    return (other.sign == +1) ? Decimal(result_sign, 0, 0) : Decimal.infinity(result_sign)
  end

  # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
  if _self.infinite?
    return (other.sign == +1) ? Decimal.infinity(result_sign) : Decimal(result_sign, 0, 0)
  end

  # 1**other = 1, but the choice of exponent and the flags
  # depend on the exponent of self, and on whether other is a
  # positive integer, a negative integer, or neither
  if _self == Decimal(1)
    return _self if context.exact?
    if other.integral?
      # exp = max(self._exp*max(int(other), 0),
      # 1-context.prec) but evaluating int(other) directly
      # is dangerous until we know other is small (other
      # could be 1e999999999)
      if other.sign == -1
        multiplier = 0
      elsif other > context.precision
        multiplier = context.precision
      else
        multiplier = other.to_i
      end

      exp = _self.integral_exponent * multiplier
      if exp < 1-context.precision
        exp = 1-context.precision
        context.exception Rounded
      end
    else
      context.exception Rounded
      context.exception Inexact
      exp = 1-context.precision
    end

    return Decimal(result_sign, Decimal.int_radix_power(-exp), exp)
  end

  # compute adjusted exponent of self
  self_adj = _self.adjusted_exponent

  # self ** infinity is infinity if self > 1, 0 if self < 1
  # self ** -infinity is infinity if self < 1, 0 if self > 1
  if other.infinite?
    if (other.sign == +1) == (self_adj < 0)
      return Decimal(result_sign, 0, 0)
    else
      return Decimal.infinity(result_sign)
    end
  end

  # from here on, the result always goes through the call
  # to _fix at the end of this function.
  ans = nil

  # crude test to catch cases of extreme overflow/underflow.  If
  # log10(self)*other >= 10**bound and bound >= len(str(Emax))
  # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
  # self**other >= 10**(Emax+1), so overflow occurs.  The test
  # for underflow is similar.
  bound = _self._log10_exp_bound + other.adjusted_exponent
  if (self_adj >= 0) == (other.sign == +1)
    # self > 1 and other +ve, or self < 1 and other -ve
    # possibility of overflow
    if bound >= context.emax.to_s.length
      ans = Decimal(result_sign, 1, context.emax+1)
    end
  else
    # self > 1 and other -ve, or self < 1 and other +ve
    # possibility of underflow to 0
    etiny = context.etiny
    if bound >= (-etiny).to_s.length
      ans = Decimal(result_sign, 1, etiny-1)
    end
  end

  # try for an exact result with precision +1
  if ans.nil?
    if context.exact?
      if other.adjusted_exponent < 100
        test_precision = _self.number_of_digits*other.to_i+1
      else
        test_precision = _self.number_of_digits+1
      end
    else
      test_precision = context.precision + 1
    end
    ans = _self._power_exact(other, test_precision)
    if !ans.nil? && (result_sign == -1)
      ans = Decimal(-1, ans.integral_significand, ans.integral_exponent)
    end
  end

  # usual case: inexact result, x**y computed directly as exp(y*log(x))
  if !ans.nil?
    return ans if context.exact?
  else
    return context.exception(Inexact, "Inexact power") if context.exact?

    p = context.precision
    xc = _self.integral_significand
    xe = _self.integral_exponent
    yc = other.integral_significand
    ye = other.integral_exponent
    yc = -yc if other.sign == -1

    # compute correctly rounded result:  start with precision +3,
    # then increase precision until result is unambiguously roundable
    extra = 3
    coeff, exp = nil, nil
    loop do
      coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
      #break if (coeff % Decimal.int_mult_radix_power(5,coeff.to_s.length-p-1)) != 0
      break if (coeff % (5*10**(coeff.to_s.length-p-1))) != 0
      extra += 3
    end
    ans = Decimal(result_sign, coeff, exp)
  end

  # the specification says that for non-integer other we need to
  # raise Inexact, even when the result is actually exact.  In
  # the same way, we need to raise Underflow here if the result
  # is subnormal.  (The call to _fix will take care of raising
  # Rounded and Subnormal, as usual.)
  if !other.integral?
    context.exception Inexact
    # pad with zeros up to length context.precision+1 if necessary
    if ans.number_of_digits <= context.precision
      expdiff = context.precision+1 - ans.number_of_digits
      ans = Decimal(ans.sign, Decimal.int_mult_radix_power(ans.integral_significand, expdiff), ans.integral_exponent-expdiff)
    end
    context.exception Underflow if ans.adjusted_exponent < context.emin
  end
  # unlike exp, ln and log10, the power function respects the
  # rounding mode; no need to use ROUND_HALF_EVEN here
  ans._fix(context)
end

#qnan?Boolean

Returns whether the number is a quite NaN (non-signaling)

Returns:



1141
1142
1143
# File 'lib/decimal/decimal.rb', line 1141

def qnan?
  @exp == :nan
end

#quantize(exp, context = nil, watch_exp = true) ⇒ Object

Quantize so its exponent is the same as that of y.



2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
# File 'lib/decimal/decimal.rb', line 2244

def quantize(exp, context=nil, watch_exp=true)
  exp = _convert(exp)
  context = Decimal.define_context(context)
  if self.special? || exp.special?
    ans = _check_nans(context, exp)
    return ans if ans
    if exp.infinite? || self.infinite?
      return Decimal.new(self) if exp.infinite? && self.infinite?
      return context.exception(InvalidOperation, 'quantize with one INF')
    end
  end
  exp = exp.integral_exponent
  _watched_rescale(exp, context, watch_exp)
end

#reduce(context = nil) ⇒ Object

Reduces an operand to its simplest form by removing trailing 0s and incrementing the exponent. (formerly called normalize in GDAS)



1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
# File 'lib/decimal/decimal.rb', line 1838

def reduce(context=nil)
  context = Decimal.define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
  end
  dup = _fix(context)
  return dup if dup.infinite?

  return Decimal.new([dup.sign, 0, 0]) if dup.zero?

  exp_max = context.clamp? ? context.etop : context.emax
  end_d = nd = dup.number_of_digits
  exp = dup.integral_exponent
  coeff = dup.integral_significand
  dgs = dup.digits
  while (dgs[end_d-1]==0) && (exp < exp_max)
    exp += 1
    end_d -= 1
  end
  return Decimal.new([dup.sign, coeff/Decimal.int_radix_power(nd-end_d), exp])

end

#remainder(other, context = nil) ⇒ Object

General Decimal Arithmetic Specification remainder: x - y*divide_int(x,y)



1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
# File 'lib/decimal/decimal.rb', line 1750

def remainder(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return ans if ans

  #sign = self.sign * other.sign

  if self.infinite?
    return context.exception(InvalidOperation, 'INF % x')
  elsif other.zero?
    if self.zero?
      return context.exception(DivisionUndefined, '0 % 0')
    else
      return context.exception(InvalidOperation, 'x % 0')
    end
  end

  return self._divide_truncate(other, context).last._fix(context)
end

#remainder_near(other, context = nil) ⇒ Object

General Decimal Arithmetic Specification remainder-near:

x - y*round_half_even(x/y)


1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
# File 'lib/decimal/decimal.rb', line 1774

def remainder_near(other, context=nil)
  context = Decimal.define_context(context)
  other = _convert(other)

  ans = _check_nans(context,other)
  return ans if ans

  sign = self.sign * other.sign

  if self.infinite?
    return context.exception(InvalidOperation, 'remainder_near(INF,x)')
  elsif other.zero?
    if self.zero?
      return context.exception(DivisionUndefined, 'remainder_near(0,0)')
    else
      return context.exception(InvalidOperation, 'remainder_near(x,0)')
    end
  end

  if other.infinite?
    return Decimal.new(self)._fix(context)
  end

  ideal_exp = [self.integral_exponent, other.integral_exponent].min
  if self.zero?
    return Decimal([self.sign, 0, ideal_exp])._fix(context)
  end

  expdiff = self.adjusted_exponent - other.adjusted_exponent
  if (expdiff >= context.precision+1) && !context.exact?
    return context.exception(DivisionImpossible)
  elsif expdiff <= -2
    return self._rescale(ideal_exp, context.rounding)._fix(context)
  end

    self_coeff = self.integral_significand
    other_coeff = other.integral_significand
    de = self.integral_exponent - other.integral_exponent
    if de >= 0
      self_coeff = Decimal.int_mult_radix_power(self_coeff, de)
    else
      other_coeff = Decimal.int_mult_radix_power(other_coeff, -de)
    end
    q, r = self_coeff.divmod(other_coeff)
    if 2*r + (q&1) > other_coeff
      r -= other_coeff
      q += 1
    end

    return context.exception(DivisionImpossible) if q >= Decimal.int_radix_power(context.precision) && !context.exact?

    sign = self.sign
    if r < 0
      sign = -sign
      r = -r
    end

  return Decimal.new([sign, r, ideal_exp])._fix(context)

end

#rescale(exp, context = nil, watch_exp = true) ⇒ Object

Rescale so that the exponent is exp, either by padding with zeros or by truncating digits.



2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
# File 'lib/decimal/decimal.rb', line 2227

def rescale(exp, context=nil, watch_exp=true)
  context = Decimal.define_context(context)
  exp = _convert(exp)
  if self.special? || exp.special?
    ans = _check_nans(context, exp)
    return ans if ans
    if exp.infinite? || self.infinite?
      return Decimal.new(self) if exp.infinite? && self.infinite?
      return context.exception(InvalidOperation, 'rescale with one INF')
    end
  end
  return context.exception(InvalidOperation,"exponent of rescale is not integral") unless exp.integral?
  exp = exp.to_i
  _watched_rescale(exp, context, watch_exp)
end

#round(opt = {}) ⇒ Object

General rounding.

With an integer argument this acts like Float#round: the parameter specifies the number of fractional digits (or digits to the left of the decimal point if negative).

Options can be passed as a Hash instead; valid options are:

  • :rounding method for rounding (see Context#new())

The precision can be specified as:

  • :places number of fractional digits as above.

  • :exponent specifies the exponent corresponding to the digit to be rounded (exponent == -places)

  • :precision or :significan_digits is the number of digits

  • :power 10^exponent, value of the digit to be rounded, should be passed as a type convertible to Decimal.

  • :index 0-based index of the digit to be rounded

  • :rindex right 0-based index of the digit to be rounded

The default is :places=>0 (round to integer).

Example: ways of specifiying the rounding position

number:     1   2   3   4  .  5    6    7    8
:places    -3  -2  -1   0     1    2    3    4
:exponent   3   2   1   0    -1   -2   -3   -4
:precision  1   2   3   4     5    6    7    8
:power    1E3 1E2  10   1   0.1 1E-2 1E-3 1E-4
:index      0   1   2   3     4    5    6    7
:index      7   6   5   4     3    2    1    0


2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
# File 'lib/decimal/decimal.rb', line 2328

def round(opt={})
  opt = { :places=>opt } if opt.kind_of?(Integer)
  r = opt[:rounding] || :half_up
  as_int = false
  if v=(opt[:precision] || opt[:significant_digits])
    prec = v
  elsif v=(opt[:places])
    prec = adjusted_exponent + 1 + v
  elsif v=(opt[:exponent])
    prec = adjusted_exponent + 1 - v
  elsif v=(opt[:power])
    prec = adjusted_exponent + 1 - Decimal(v).adjusted_exponent
  elsif v=(opt[:index])
    prec = i+1
  elsif v=(opt[:rindex])
    prec = number_of_digits - v
  else
    prec = adjusted_exponent + 1
    as_int = true
  end
  result = plus(:rounding=>r, :precision=>prec)
  return as_int ? result.to_i : result
end

#same_quantum?(other) ⇒ Boolean

Return true if has the same exponent as other.

If either operand is a special value, the following rules are used:

  • return true if both operands are infinities

  • return true if both operands are NaNs

  • otherwise, return false.

Returns:



2265
2266
2267
2268
2269
2270
2271
# File 'lib/decimal/decimal.rb', line 2265

def same_quantum?(other)
  other = _convert(other)
  if self.special? || other.special?
    return (self.nan? && other.nan?) || (self.infinite? && other.infinite?)
  end
  return self.integral_exponent == other.integral_exponent
end

#scaleb(other, context = nil) ⇒ Object

Adds a value to the exponent.



1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
# File 'lib/decimal/decimal.rb', line 1878

def scaleb(other, context=nil)

  context = Decimal.define_context(context)
  other = _convert(other)
  ans = _check_nans(context, other)
  return ans if ans
  return context.exception(InvalidOperation) if other.infinite? || other.integral_exponent != 0
  unless context.exact?
    liminf = -2 * (context.emax + context.precision)
    limsup =  2 * (context.emax + context.precision)
    i = other.to_i
    return context.exception(InvalidOperation) if !((liminf <= i) && (i <= limsup))
  end
  return Decimal.new(self) if infinite?
  return Decimal.new(@sign, @coeff, @exp+i)._fix(context)

end

#scientific_exponentObject

Synonym for Decimal#adjusted_exponent()



2103
2104
2105
# File 'lib/decimal/decimal.rb', line 2103

def scientific_exponent
  adjusted_exponent
end

#signObject

Sign of the number: +1 for plus / -1 for minus.



2130
2131
2132
# File 'lib/decimal/decimal.rb', line 2130

def sign
  @sign
end

#snan?Boolean

Returns whether the number is a signaling NaN

Returns:



1146
1147
1148
# File 'lib/decimal/decimal.rb', line 1146

def snan?
  @exp == :snan
end

#special?Boolean

Returns whether the number is a special value (NaN or Infinity).

Returns:



1131
1132
1133
# File 'lib/decimal/decimal.rb', line 1131

def special?
  @exp.instance_of?(Symbol)
end

#splitObject

Returns the internal representation of the number, composed of:

  • a sign which is +1 for plus and -1 for minus

  • a coefficient (significand) which is an integer

  • an exponent (an integer) or :inf, :nan or :snan for special values

The value of non-special numbers is sign*coefficient*10^exponent



1126
1127
1128
# File 'lib/decimal/decimal.rb', line 1126

def split
  [@sign, @coeff, @exp]
end

#sqrt(context = nil) ⇒ Object

Square root



1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
# File 'lib/decimal/decimal.rb', line 1553

def sqrt(context=nil)
  context = Decimal.define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    return Decimal.new(self) if infinite? && @sign==+1
  end
  return Decimal.new([@sign, 0, @exp/2])._fix(context) if zero?
  return context.exception(InvalidOperation, 'sqrt(-x), x>0') if @sign<0
  prec = context.precision + 1
  e = (@exp >> 1)
  if (@exp & 1)!=0
    c = @coeff*Decimal.radix
    l = (number_of_digits >> 1) + 1
  else
    c = @coeff
    l = (number_of_digits+1) >> 1
  end
  shift = prec - l
  if shift >= 0
    c = Decimal.int_mult_radix_power(c, (shift<<1))
    exact = true
  else
    c, remainder = c.divmod(Decimal.int_radix_power((-shift)<<1))
    exact = (remainder==0)
  end
  e -= shift

  n = Decimal.int_radix_power(prec)
  while true
    q = c / n
    break if n <= q
    n = ((n + q) >> 1)
  end
  exact = exact && (n*n == c)

  if exact
    if shift >= 0
      n = Decimal.int_div_radix_power(n, shift)
    else
      n = Decimal.int_mult_radix_power(n, -shift)
    end
    e += shift
  else
    return context.exception(Inexact) if context.exact?
    n += 1 if (n%5)==0
  end
  ans = Decimal.new([+1,n,e])
  Decimal.local_context(:rounding=>:half_even) do
    ans = ans._fix(context)
  end
  return ans
end

#subnormal?(context = nil) ⇒ Boolean

Returns whether the number is subnormal

Returns:



1171
1172
1173
1174
1175
# File 'lib/decimal/decimal.rb', line 1171

def subnormal?(context=nil)
  return false if special? || zero?
  context = Decimal.define_context(context)
  self.adjusted_exponent < context.emin
end

#subtract(other, context = nil) ⇒ Object

Subtraction



1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
# File 'lib/decimal/decimal.rb', line 1341

def subtract(other, context=nil)

  context = Decimal.define_context(context)
  other = _convert(other)

  if self.special? || other.special?
    ans = _check_nans(context,other)
    return ans if ans
  end
  return add(other.copy_negate, context)
end

#to_fObject

Conversion to Float



1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
# File 'lib/decimal/decimal.rb', line 1985

def to_f
  if special?
    if @exp==:inf
      @sign/0.0
    else
      0.0/0.0
    end
  else
    # to_rational.to_f
    # to_s.to_f
    @sign*@coeff*(10.0**@exp)
  end
end

#to_iObject

Ruby-style to integer conversion.



1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
# File 'lib/decimal/decimal.rb', line 1903

def to_i
  if special?
    if nan?
      #return Decimal.context.exception(InvalidContext)
      Decimal.context.exception InvalidContext
      return nil
    end
    raise Error, "Cannot convert infinity to Integer"
  end
  if @exp >= 0
    return @sign*Decimal.int_mult_radix_power(@coeff,@exp)
  else
    return @sign*Decimal.int_div_radix_power(@coeff,-@exp)
  end
end

#to_int_scaleObject

Return the value of the number as an integer and a scale.



2135
2136
2137
2138
2139
2140
2141
# File 'lib/decimal/decimal.rb', line 2135

def to_int_scale
  if special?
    nil
  else
    [@sign*integral_significand, integral_exponent]
  end
end

#to_integral_exact(context = nil) ⇒ Object

Rounds to a nearby integer. May raise Inexact or Rounded.



2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
# File 'lib/decimal/decimal.rb', line 2274

def to_integral_exact(context=nil)
  context = Decimal.define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    return Decimal.new(self)
  end
  return Decimal.new(self) if @exp >= 0
  return Decimal.new([@sign, 0, 0]) if zero?
  context.exception Rounded
  ans = _rescale(0, context.rounding)
  context.exception Inexact if ans != self
  return ans
end

#to_integral_value(context = nil) ⇒ Object

Rounds to a nearby integer. Doesn’t raise Inexact or Rounded.



2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
# File 'lib/decimal/decimal.rb', line 2290

def to_integral_value(context=nil)
  context = Decimal.define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    return Decimal.new(self)
  end
  return Decimal.new(self) if @exp >= 0
  return _rescale(0, context.rounding)
end

#to_rObject

Conversion to Rational. Conversion of special values will raise an exception under Ruby 1.9



1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
# File 'lib/decimal/decimal.rb', line 1971

def to_r
  if special?
    num = (@exp == :inf) ? @sign : 0
    Rational.respond_to?(:new!) ? Rational.new!(num,0) : Rational(num,0)
  else
    if @exp < 0
      Rational(@sign*@coeff, Decimal.int_radix_power(-@exp))
    else
      Rational(Decimal.int_mult_radix_power(@sign*@coeff,@exp), 1)
    end
  end
end

#to_s(eng = false, context = nil) ⇒ Object

Ruby-style to string conversion.



1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
# File 'lib/decimal/decimal.rb', line 1920

def to_s(eng=false,context=nil)
  # (context || Decimal.context).to_string(self)
  context = Decimal.define_context(context)
  sgn = sign<0 ? '-' : ''
  if special?
    if @exp==:inf
      "#{sgn}Infinity"
    elsif @exp==:nan
      "#{sgn}NaN#{@coeff}"
    else # exp==:snan
      "#{sgn}sNaN#{@coeff}"
    end
  else
    ds = @coeff.to_s
    n_ds = ds.size
    exp = integral_exponent
    leftdigits = exp + n_ds
    if exp<=0 && leftdigits>-6
      dotplace = leftdigits
    elsif !eng
      dotplace = 1
    elsif @coeff==0
      dotplace = (leftdigits+1)%3 - 1
    else
      dotplace = (leftdigits-1)%3 + 1
    end

    if dotplace <=0
      intpart = '0'
      fracpart = '.' + '0'*(-dotplace) + ds
    elsif dotplace >= n_ds
      intpart = ds + '0'*(dotplace - n_ds)
      fracpart = ''
    else
      intpart = ds[0...dotplace]
      fracpart = '.' + ds[dotplace..-1]
    end

    if leftdigits == dotplace
      e = ''
    else
      e = (context.capitals ? 'E' : 'e') + "%+d"%(leftdigits-dotplace)
    end

    sgn + intpart + fracpart + e

  end
end

#truncate(opt = {}) ⇒ Object

General truncate operation (as for Float) with same options for precision as Decimal#round()



2368
2369
2370
2371
# File 'lib/decimal/decimal.rb', line 2368

def truncate(opt={})
  opt[:rounding] = :down
  round opt
end

#zero?Boolean

Returns whether the number is zero

Returns:



1161
1162
1163
# File 'lib/decimal/decimal.rb', line 1161

def zero?
  @coeff==0 && !special?
end