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.



1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
# File 'lib/decimal/decimal.rb', line 1165

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
  args = args.first if args.size==1 && args.first.is_a?(Array)

  context = Decimal.define_context(context)

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

  when 2
    # signed integer and scale
    @coeff, @exp = args
    if @coeff < 0
      @sign = -1
      @coeff = -@coeff
    else
      @sign = +1
    end

  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
    else
      raise TypeError, "invalid argument #{arg.inspect}"
    end
  else
    raise ArgumentError, "wrong number of arguments (#{args.size} for 1, 2 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().



1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
# File 'lib/decimal/decimal.rb', line 1003

def Decimal.context(*args, &blk)
  if blk
    # setup a local context
    local_context(*args, &blk)
  elsif args.empty?
    # return the current context
    self._context = DefaultContext.dup if _context.nil?
    _context
  else
    # change the current context
    # TODO: consider doing _context = ... here
    # so we would have Decimal.context = c that assigns a duplicate of c
    # and Decimal.context c to set alias c
    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



955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
# File 'lib/decimal/decimal.rb', line 955

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).



1021
1022
1023
# File 'lib/decimal/decimal.rb', line 1021

def Decimal.context=(c)
  self._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



989
990
991
992
993
994
995
996
997
# File 'lib/decimal/decimal.rb', line 989

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



1061
1062
1063
# File 'lib/decimal/decimal.rb', line 1061

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.



1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/decimal/decimal.rb', line 1029

def Decimal.local_context(*args)
  keep = Decimal.context # use this so _context is initialized if necessary
  Decimal.context = define_context(*args) # this dups the assigned context
  result = yield _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)
  self._context = keep
  result
end

.nanObject

A decimal NaN (not a number)



1066
1067
1068
# File 'lib/decimal/decimal.rb', line 1066

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



1056
1057
1058
# File 'lib/decimal/decimal.rb', line 1056

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

Instance Method Details

#%(other, context = nil) ⇒ Object

Modulo of two decimal numbers



1407
1408
1409
# File 'lib/decimal/decimal.rb', line 1407

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

#*(other, context = nil) ⇒ Object

Multiplication of two decimal numbers



1397
1398
1399
# File 'lib/decimal/decimal.rb', line 1397

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

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

Power



1412
1413
1414
# File 'lib/decimal/decimal.rb', line 1412

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

#+(other, context = nil) ⇒ Object

Addition of two decimal numbers



1387
1388
1389
# File 'lib/decimal/decimal.rb', line 1387

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

#+@(context = nil) ⇒ Object

Unary plus operator



1381
1382
1383
1384
# File 'lib/decimal/decimal.rb', line 1381

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

#-(other, context = nil) ⇒ Object

Subtraction of two decimal numbers



1392
1393
1394
# File 'lib/decimal/decimal.rb', line 1392

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

#-@(context = nil) ⇒ Object

Unary minus operator



1375
1376
1377
1378
# File 'lib/decimal/decimal.rb', line 1375

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

#/(other, context = nil) ⇒ Object

Division of two decimal numbers



1402
1403
1404
# File 'lib/decimal/decimal.rb', line 1402

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.



2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
# File 'lib/decimal/decimal.rb', line 2206

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.coefficient,other.coefficient
          d = self.exponent - other.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 !self.nan? && defined? other.coerce
      x, y = other.coerce(self)
      x <=> y
    else
      nil
    end
  end
end

#==(other) ⇒ Object



2259
2260
2261
# File 'lib/decimal/decimal.rb', line 2259

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

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

Returns a copy with positive sign



3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
# File 'lib/decimal/decimal.rb', line 3091

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.



2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
# File 'lib/decimal/decimal.rb', line 2988

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.



3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
# File 'lib/decimal/decimal.rb', line 3107

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.coefficient, 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.exponent< etop
          ans = Decimal.new([ans.sign, Decimal.int_div_radix_power(ans.coefficient,1), ans.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



3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
# File 'lib/decimal/decimal.rb', line 3190

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



3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
# File 'lib/decimal/decimal.rb', line 3061

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



3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
# File 'lib/decimal/decimal.rb', line 3076

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



3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
# File 'lib/decimal/decimal.rb', line 3011

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.exponent - exp), exp]) if self.exponent > exp
  #nd = number_of_digits + self.exponent - exp
  nd = exp - self.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



3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
# File 'lib/decimal/decimal.rb', line 3031

def _watched_rescale(exp, context, watch_exp)
  if !watch_exp
    ans = _rescale(exp, context.rounding)
    context.exception(Rounded) if ans.exponent > self.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.exponent > self.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



1578
1579
1580
1581
1582
1583
1584
# File 'lib/decimal/decimal.rb', line 1578

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



1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
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 1417

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.exponent, other.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.exponent - context.precision - 1].max unless context.exact?
    return other._rescale(exp, context.rounding)._fix(context)
  end

  if other.zero?
    exp = [exp, self.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.coefficient == op2.coefficient
    op1,op2 = op2,op1 if op1.coefficient < op2.coefficient
    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.coefficient + op2.coefficient
  else
    result_coeff = op1.coefficient - op2.coefficient
  end

  result_exp = op1.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



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

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()



2568
2569
2570
2571
# File 'lib/decimal/decimal.rb', line 2568

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

#coefficientObject

Significand as an integer, unsigned



2334
2335
2336
# File 'lib/decimal/decimal.rb', line 2334

def coefficient
  @coeff
end

#coerce(other) ⇒ Object

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



1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
# File 'lib/decimal/decimal.rb', line 1350

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

#compare(other, context = nil) ⇒ Object

Compares like <=> but returns a Decimal value.



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

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.



2056
2057
2058
2059
# File 'lib/decimal/decimal.rb', line 2056

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 +



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

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

#copy_negateObject

Returns a copy of with the sign inverted



2358
2359
2360
# File 'lib/decimal/decimal.rb', line 2358

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

#copy_sign(other) ⇒ Object

Returns a copy of with the sign of other



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

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

#digitsObject

Digits of the significand as an array of integers



2288
2289
2290
# File 'lib/decimal/decimal.rb', line 2288

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

#div(other, context = nil) ⇒ Object

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



1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
# File 'lib/decimal/decimal.rb', line 1845

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



1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
# File 'lib/decimal/decimal.rb', line 1527

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.exponent - other.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.exponent - other.exponent - shift
    if shift >= 0
      coeff, remainder = (self.coefficient*Decimal.int_radix_power(shift)).divmod(other.coefficient)
    else
      coeff, remainder = self.coefficient.divmod(other.coefficient*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.exponent - other.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



1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
# File 'lib/decimal/decimal.rb', line 1820

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



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
# File 'lib/decimal/decimal.rb', line 1786

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


1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
# File 'lib/decimal/decimal.rb', line 1753

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:

  • (Boolean)


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

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:

  • (Boolean)


2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
# File 'lib/decimal/decimal.rb', line 2386

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



2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
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
# File 'lib/decimal/decimal.rb', line 2868

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.coefficient
    e = self.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

#exponentObject

Exponent of the significand as an integer.



2339
2340
2341
# File 'lib/decimal/decimal.rb', line 2339

def exponent
  @exp
end

#finite?Boolean

Returns whether the number is finite

Returns:

  • (Boolean)


1298
1299
1300
# File 'lib/decimal/decimal.rb', line 1298

def finite?
  !special?
end

#floor(opt = {}) ⇒ Object

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



2575
2576
2577
2578
# File 'lib/decimal/decimal.rb', line 2575

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.



2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
# File 'lib/decimal/decimal.rb', line 2590

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.coefficient*other.coefficient, self.exponent+other.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)



2307
2308
2309
# File 'lib/decimal/decimal.rb', line 2307

def fractional_exponent
  scientific_exponent + 1
end

#hashObject



2264
2265
2266
# File 'lib/decimal/decimal.rb', line 2264

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

#infinite?Boolean

Returns whether the number is infinite

Returns:

  • (Boolean)


1293
1294
1295
# File 'lib/decimal/decimal.rb', line 1293

def infinite?
  @exp == :inf
end

#inspectObject



2196
2197
2198
2199
2200
2201
2202
# File 'lib/decimal/decimal.rb', line 2196

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

#integral?Boolean

Returns true if the value is an integer

Returns:

  • (Boolean)


2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
# File 'lib/decimal/decimal.rb', line 2368

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. Synonym of exponent



2323
2324
2325
2326
# File 'lib/decimal/decimal.rb', line 2323

def integral_exponent
  # fractional_exponent - number_of_digits
  @exp
end

#integral_significandObject

Significand as an integer, unsigned. Synonym of coefficient



2318
2319
2320
# File 'lib/decimal/decimal.rb', line 2318

def integral_significand
  @coeff
end

#ln(context = nil) ⇒ Object

Returns the natural (base e) logarithm



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
2974
2975
2976
2977
2978
2979
2980
2981
2982
# File 'lib/decimal/decimal.rb', line 2939

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.coefficient
  e = self.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



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
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
# File 'lib/decimal/decimal.rb', line 2818

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.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.coefficient
    e = self.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).



2027
2028
2029
2030
2031
2032
2033
2034
# File 'lib/decimal/decimal.rb', line 2027

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



1592
1593
1594
# File 'lib/decimal/decimal.rb', line 1592

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

#modulo(other, context = nil) ⇒ Object

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



1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
# File 'lib/decimal/decimal.rb', line 1871

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



1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
# File 'lib/decimal/decimal.rb', line 1498

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.exponent + other.exponent

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

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

end

#nan?Boolean

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

Returns:

  • (Boolean)


1278
1279
1280
# File 'lib/decimal/decimal.rb', line 1278

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

#next_minus(context = nil) ⇒ Object

Largest representable number smaller than itself



1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
# File 'lib/decimal/decimal.rb', line 1597

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



1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
# File 'lib/decimal/decimal.rb', line 1628

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.



1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
# File 'lib/decimal/decimal.rb', line 1661

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:

  • (Boolean)


1308
1309
1310
# File 'lib/decimal/decimal.rb', line 1308

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

#normal?(context = nil) ⇒ Boolean

Returns whether the number is normal

Returns:

  • (Boolean)


1320
1321
1322
1323
1324
# File 'lib/decimal/decimal.rb', line 1320

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

#normalize(context = nil) ⇒ Object

normalizes so that the coefficient has precision digits (this is not the old GDA normalize function)



2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
# File 'lib/decimal/decimal.rb', line 2007

def normalize(context=nil)
  context = Decimal.define_context(context)
  return Decimal(self) if self.special? || self.zero?
  return context.exception(InvalidOperation, "Normalize in exact context") if context.exact?
  return context.exception(Subnormal, "Cannot normalize subnormal") if self.subnormal?
  min_normal_coeff = Decimal.int_radix_power(context.precision-1)
  sign, coeff, exp = self._fix(context).split
  while coeff < min_normal_coeff
    coeff *= Decimal.radix
    exp -= 1
  end
  Decimal(sign, coeff, exp)
end

#number_class(context = nil) ⇒ Object

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

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


1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# File 'lib/decimal/decimal.rb', line 1329

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



2312
2313
2314
2315
# File 'lib/decimal/decimal.rb', line 2312

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

#odd?Boolean

returns true if is an odd integer

Returns:

  • (Boolean)


2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
# File 'lib/decimal/decimal.rb', line 2410

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



1587
1588
1589
# File 'lib/decimal/decimal.rb', line 1587

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.



2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
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
2723
2724
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
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
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 2634

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.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.coefficient, ans.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.coefficient
    xe = _self.exponent
    yc = other.coefficient
    ye = other.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.coefficient, expdiff), ans.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:

  • (Boolean)


1283
1284
1285
# File 'lib/decimal/decimal.rb', line 1283

def qnan?
  @exp == :nan
end

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

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



2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
# File 'lib/decimal/decimal.rb', line 2453

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.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)



1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
# File 'lib/decimal/decimal.rb', line 1982

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.exponent
  coeff = dup.coefficient
  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)



1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
# File 'lib/decimal/decimal.rb', line 1894

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)


1918
1919
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
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
# File 'lib/decimal/decimal.rb', line 1918

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.exponent, other.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.coefficient
    other_coeff = other.coefficient
    de = self.exponent - other.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.



2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
# File 'lib/decimal/decimal.rb', line 2436

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


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
# File 'lib/decimal/decimal.rb', line 2537

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
  dg = number_of_digits-prec
  changed = _round(r, dg)
  coeff = Decimal.int_div_radix_power(@coeff, dg)
  exp = @exp + dg
  coeff += 1 if changed==1
  result = Decimal(@sign, coeff, exp)
  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:

  • (Boolean)


2474
2475
2476
2477
2478
2479
2480
# File 'lib/decimal/decimal.rb', line 2474

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

#scaleb(other, context = nil) ⇒ Object

Adds a value to the exponent.



2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
# File 'lib/decimal/decimal.rb', line 2037

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.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()



2302
2303
2304
# File 'lib/decimal/decimal.rb', line 2302

def scientific_exponent
  adjusted_exponent
end

#signObject

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



2329
2330
2331
# File 'lib/decimal/decimal.rb', line 2329

def sign
  @sign
end

#snan?Boolean

Returns whether the number is a signaling NaN

Returns:

  • (Boolean)


1288
1289
1290
# File 'lib/decimal/decimal.rb', line 1288

def snan?
  @exp == :snan
end

#special?Boolean

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

Returns:

  • (Boolean)


1273
1274
1275
# File 'lib/decimal/decimal.rb', line 1273

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 a nonnegative integer

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

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



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

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

#sqrt(context = nil) ⇒ Object

Square root



1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
# File 'lib/decimal/decimal.rb', line 1697

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:

  • (Boolean)


1313
1314
1315
1316
1317
# File 'lib/decimal/decimal.rb', line 1313

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



1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'lib/decimal/decimal.rb', line 1485

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



2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
# File 'lib/decimal/decimal.rb', line 2144

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.



2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
# File 'lib/decimal/decimal.rb', line 2062

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 signed integer and a scale.



2344
2345
2346
2347
2348
2349
2350
# File 'lib/decimal/decimal.rb', line 2344

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.



2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
# File 'lib/decimal/decimal.rb', line 2483

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.



2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
# File 'lib/decimal/decimal.rb', line 2499

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



2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
# File 'lib/decimal/decimal.rb', line 2130

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.



2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
# File 'lib/decimal/decimal.rb', line 2079

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()



2582
2583
2584
2585
# File 'lib/decimal/decimal.rb', line 2582

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

#ulp(context = nil) ⇒ Object

ulp (unit in the last place) according to the definition proposed by J.M. Muller in “On the definition of ulp(x)” INRIA No. 5504



2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
# File 'lib/decimal/decimal.rb', line 2160

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

  return context.exception(InvalidOperation, "ulp in exact context") if context.exact?

  if self.nan?
    return Decimal(self)
  elsif self.infinite?
    # The ulp here is context.maximum_finite - context.maximum_finite.next_minus
    return Decimal(+1, 1, context.etop)
  elsif self.zero? || self.adjusted_exponent <= context.emin
    # This is the ulp value for self.abs <= context.minimum_normal*Decimal.context
    # Here we use it for self.abs < context.minimum_normal*Decimal.context;
    #  because of the simple exponent check; the remaining cases are handled below.
    return context.minimum_nonzero
  else
    # The next can compute the ulp value for the values that
    #   self.abs > context.minimum_normal && self.abs <= context.maximum_finite
    # The cases self.abs < context.minimum_normal*Decimal.context have been handled above.

    # assert self.normal? && self.abs>context.minimum_nonzero
    norm = self.normalize
    exp = norm.integral_exponent
    sig = norm.integral_significand

    # Powers of the radix, r**n, are between areas with different ulp values: r**(n-p-1) and r**(n-p)
    # (p is context.precision).
    # This method and the ulp definitions by Muller, Kahan and Harrison assign the smaller ulp value
    # to r**n; the definition by Goldberg assigns it to the larger ulp.
    # The next line selects the smaller ulp for powers of the radix:
    exp -= 1 if sig == Decimal.int_radix_power(context.precision-1)

    return Decimal(+1, 1, exp)
  end
end

#zero?Boolean

Returns whether the number is zero

Returns:

  • (Boolean)


1303
1304
1305
# File 'lib/decimal/decimal.rb', line 1303

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