Class: Flt::Num

Inherits:
Numeric show all
Extended by:
AuxiliarFunctions, Support
Includes:
Comparable, AuxiliarFunctions, Support::AuxiliarFunctions
Defined in:
lib/flt/num.rb,
lib/flt/complex.rb

Overview

ComplexContext

Direct Known Subclasses

BinNum, DecNum

Defined Under Namespace

Modules: AuxiliarFunctions Classes: Clamped, ContextBase, 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)

Constants included from AuxiliarFunctions

AuxiliarFunctions::EXP_INC, AuxiliarFunctions::LOG10_LB_CORRECTION, AuxiliarFunctions::LOG10_MULT, AuxiliarFunctions::LOG2_LB_CORRECTION, AuxiliarFunctions::LOG2_MULT, AuxiliarFunctions::LOG_PREC_INC, AuxiliarFunctions::LOG_RADIX_EXTRA, AuxiliarFunctions::LOG_RADIX_INC

Constants included from Support::AuxiliarFunctions

Support::AuxiliarFunctions::NBITS_BLOCK, Support::AuxiliarFunctions::NBITS_LIMIT, Support::AuxiliarFunctions::NDIGITS_BLOCK, Support::AuxiliarFunctions::NDIGITS_LIMIT

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Support

FlagValues, adjust_digits, simplified_round_mode

Methods included from AuxiliarFunctions

_convert, _div_nearest, _exp, _iexp, _ilog, _log, _log_radix_digits, _log_radix_lb, _log_radix_mult, _normalize, _number_of_digits, _parser, _power, _rshift_nearest, _sqrt_nearest, log10_lb, log2_lb

Methods included from Support::AuxiliarFunctions

_nbits, _ndigits, detect_float_rounding

Constructor Details

#initialize(*args) ⇒ Num

A floating point-number value can be defined by:

  • A String containing a text representation of the number

  • An Integer

  • A Rational

  • For binary floating point: a Float

  • A Value of a type for which conversion is defined in the context.

  • Another floating-point value of the same type.

  • A sign, coefficient and exponent (either as separate arguments, as an array or as a Hash with symbolic keys), or a signed coefficient and an exponent. This is the internal representation of Num, as returned by Num#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 after the value-definint argument to override the current context and options can be passed in a last hash argument; alternatively context options can be overriden by options of the hash argument.

When the number is defined by a numeric literal (a String), it can be followed by a symbol that specifies the mode used to convert the literal to a floating-point value:

  • :free is currently the default for all cases. The precision of the input literal (including trailing zeros) is preserved and the precision of the context is ignored. When the literal is in the same base as the floating-point radix, (which, by default, is the case for DecNum only), the literal is preserved exactly in floating-point. Otherwise, all significative digits that can be derived from the literal are generanted, significative meaning here that if the digit is changed and the value converted back to a literal of the same base and precision, the original literal will not be obtained.

  • :short is a variation of :free in which only the minimun number of digits that are necessary to produce the original literal when the value is converted back with the same original precision; namely, given an input in base b1, its :short representation in base 2 is the shortest number in base b2 such that when converted back to base b2 with the same precision that the input had, the result is identical to the input:

    short = Num[b2].new(input, :short, base: b1)
    Num[b1].context.precision = precision_of_inpu
    Num[b1].new(short.to_s(base: b2), :fixed, base: b2)) == Num[b1].new(input, :free, base: b1)
    
  • :fixed will round and normalize the value to the precision specified by the context (normalize meaning that exaclty the number of digits specified by the precision will be generated, even if the original literal has fewer digits.) This may fail returning NaN (and raising Inexact) if the context precision is :exact, but not if the floating-point radix is a multiple of the input base.

Options that can be passed for construction from literal:

  • :base is the numeric base of the input, 10 by default.



1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
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
1515
1516
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
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
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
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
# File 'lib/flt/num.rb', line 1472

def initialize(*args)
  options = args.pop if args.last.is_a?(Hash)
  context = args.pop if args.size>0 && (args.last.kind_of?(ContextBase) || args.last.nil?)
  context ||= options && options.delete(:context)
  mode = args.pop if args.last.is_a?(Symbol) && ![:inf, :nan, :snan].include?(args.last)
  args = args.first if args.size==1 && args.first.is_a?(Array)
  if args.empty? && options
    args = [options.delete(:sign)||+1,
            options.delete(:coefficient) || 0,
            options.delete(:exponent) || 0]
  end
  mode ||= options && options.delete(:mode)
  base = (options && options.delete(:base))
  context = options if context.nil? && options && !options.empty?
  context = 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 num_class
      @sign, @coeff, @exp = arg.split

    when *context.coercible_types
      v = context._coerce(arg)
      @sign, @coeff, @exp = v.is_a?(Num) ? 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, :base => base)
      if m.nil?
        @sign,@coeff,@exp = context.exception(ConversionSyntax, "Invalid literal for DecNum: #{arg.inspect}").split
        return
      end
      @sign = (m.sign == '-') ? -1 : +1
      if m.int || m.onlyfrac
        sign = @sign
        if m.int
          intpart = m.int
          fracpart = m.frac
        else
          intpart = ''
          fracpart = m.onlyfrac
        end
        fracpart ||= ''
        base = m.base
        exp = m.exp.to_i
        coeff = (intpart+fracpart).to_i(base)
        if m.exp_base && m.exp_base != base
          # The exponent uses a different base;
          # compute exponent in base; assume base = exp_base**k
          k = Math.log(base, m.exp_base).round
          exp -= fracpart.size*k
          base = m.exp_base
        else
          exp -= fracpart.size
        end

        if false
          # Old behaviour: use :fixed format when num_class.radix != base
          # Advantages:
          # * Behaviour similar to Float: BinFloat(txt) == Float(txt)
          mode ||= ((num_class.radix == base) ? :free : :fixed)
        else
          # New behaviour: the default is always :free
          # Advantages:
          # * Is coherent with construction of DecNum from decimal literal:
          #   preserve precision of the literal with independence of context.
          mode ||= :free
        end

        if mode == :free && base == num_class.radix
          # simple case, the job is already done
          #
          # :free mode with same base must not be handled by the Reader;
          # note that if we used the Reader for the same base case in :free mode,
          # an extra 'significative' digit would be added, because that digit
          # is significative in the sense that (under non-directed rounding,
          # and with the significance interpretation of Reader wit the all-digits option)
          # it's not free to take any value without affecting the value of
          # the other digits: e.g. input: '0.1', the result of :free
          # conversion with the Reader is '0.10' because de last digit is not free;
          # if it was 9 for example the actual value would round to '0.2' with the input
          # precision given here.
          #
          # On the other hand, :short, should be handled by the Reader even when
          # the input and output bases are the same because we want to find the shortest
          # number that can be converted back to the input with the same input precision.
        else
          rounding = context.rounding
          reader = Support::Reader.new(:mode=>mode)
          ans = reader.read(context, rounding, sign, coeff, exp, base)
          context.exception(Inexact,"Inexact decimal to radix #{num_class.radix} conversion") if !reader.exact?
          if !reader.exact? && context.exact?
            sign, coeff, exp =  num_class.nan.split
          else
            sign, coeff, exp = ans.split
          end
        end
        @sign, @coeff, @exp = sign, coeff, exp
      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 >= context.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.



174
175
176
# File 'lib/flt/num.rb', line 174

def _base_coercible_types
  @_base_coercible_types
end

._base_conversionsObject (readonly)

Returns the value of attribute _base_conversions.



175
176
177
# File 'lib/flt/num.rb', line 175

def _base_conversions
  @_base_conversions
end

Class Method Details

.[](*args) ⇒ Object

Num can be use to obtain a floating-point numeric class with radix base, so that, for example, Num is equivalent to BinNum and Num to DecNum.

If the base does not correspond to one of the predefined classes (DecNum, BinNum), a new class is dynamically generated.

The [] operator can also be applied to classes derived from Num to act as a constructor (short hand for .new):

Flt::Num[10]['0.1'] # same as FLt::DecNum['0.1'] or Flt.DecNum('0.1') or Flt::DecNum.new('0.1')

Raises:

  • (RuntimeError)


4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
# File 'lib/flt/num.rb', line 4609

def [](*args)
  return self.Num(*args) if self!=Num # && self.ancestors.include?(Num)
  raise RuntimeError, "Invalid number of arguments (#{args.size}) for Num.[]; 1 expected." unless args.size==1
  base = args.first

  case base
  when 10
    DecNum
  when 2
    BinNum
  else
    class_name = "Base#{base}Num"
    unless Flt.const_defined?(class_name)
      cls = Flt.const_set class_name, Class.new(Num) {
        def initialize(*args)
          super(*args)
        end
      }
      meta_cls = class <<cls;self;end
      meta_cls.send :define_method, :radix do
        base
      end

      cls.const_set :Context, Class.new(Num::ContextBase)
      cls::Context.send :define_method, :initialize do |*options|
        super(cls, *options)
      end

      default_digits = 10
      default_elimit = 100

      cls.const_set :DefaultContext, cls::Context.new(
        :exact=>false, :precision=>default_digits, :rounding=>:half_even,
        :elimit=>default_elimit,
        :flags=>[],
        :traps=>[DivisionByZero, Overflow, InvalidOperation],
        :ignored_flags=>[],
        :capitals=>true,
        :clamp=>true,
        :angle=>:rad
      )

    end
    Flt.const_get class_name

  end
end

.base_coercible_typesObject



176
177
178
# File 'lib/flt/num.rb', line 176

def base_coercible_types
  Num._base_coercible_types
end

.base_conversionsObject



179
180
181
# File 'lib/flt/num.rb', line 179

def base_conversions
  Num._base_conversions
end

.ccontext(*args) ⇒ Object



274
275
276
# File 'lib/flt/complex.rb', line 274

def self.ccontext(*args)
  ComplexContext(self.context(*args))
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.

Note that this method should be called on concrete floating point types such as Flt::DecNum and Flt::BinNum, and not in the abstract base class Flt::Num.

See Flt::Num::ContextBase#new() for the valid options



1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
# File 'lib/flt/num.rb', line 1265

def self.Context(*args)
  case args.size
    when 0
      base = self::DefaultContext
    when 1
      arg = args.first
      if arg.instance_of?(self::Context)
        base = arg
        options = nil
      elsif arg.instance_of?(Hash)
        base = self::DefaultContext
        options = arg
      else
        raise TypeError,"invalid argument for #{num_class}.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
    self::Context.new(base, options)
  end

end

.context(*args, &blk) ⇒ Object

The current context (thread-local). If arguments are passed they are interpreted as in Num.define_context() and an altered copy of the current context is returned. If a block is given, this method is a synonym for Num.local_context().



1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
# File 'lib/flt/num.rb', line 1319

def self.context(*args, &blk)
  if blk
    # setup a local context
    local_context(*args, &blk)
  elsif args.empty?
    # return the current context
    ctxt = self._context
    self._context = ctxt = self::DefaultContext.dup if ctxt.nil?
    ctxt
  else
    # Return a modified copy of the current context
    if args.first.kind_of?(ContextBase)
      self.define_context(*args)
    else
      self.define_context(self.context, *args)
    end
  end
end

.context=(c) ⇒ Object

Change the current context (thread-local).



1339
1340
1341
# File 'lib/flt/num.rb', line 1339

def self.context=(c)
  self._context = c.dup
end

.define_context(*options) ⇒ Object

Define a context by passing either of:

  • A Context object (of the same type)

  • 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



1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/flt/num.rb', line 1299

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

.Flags(*values) ⇒ Object



397
398
399
# File 'lib/flt/num.rb', line 397

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

.infinity(sign = +1) ⇒ Object

A floating-point infinite number with the specified sign



1399
1400
1401
# File 'lib/flt/num.rb', line 1399

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

.int_div_radix_power(x, n) ⇒ Object



1421
1422
1423
# File 'lib/flt/num.rb', line 1421

def int_div_radix_power(x,n)
  n < 0 ? (x * self.radix**(-n) ) : (x / self.radix**n)
end

.int_mult_radix_power(x, n) ⇒ Object



1417
1418
1419
# File 'lib/flt/num.rb', line 1417

def int_mult_radix_power(x,n)
  n < 0 ? (x / self.radix**(-n)) : (x * self.radix**n)
end

.int_radix_power(n) ⇒ Object



1413
1414
1415
# File 'lib/flt/num.rb', line 1413

def int_radix_power(n)
  self.radix**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.



1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
# File 'lib/flt/num.rb', line 1352

def self.local_context(*args)
  begin
    keep = self.context # use this so _context is initialized if necessary
    self.context = define_context(*args) # this dups the assigned context
    result = yield _context
  ensure
    # TODO: consider the convenience of copying the flags from DecNum.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 = DecNum.context.flags
    # Another alternative to consider: logically or the flags:
    #   keep.flags ||= DecNum.context.flags # (this requires implementing || in Flags)
    self._context = keep
    result
  end
end

.math(*args, &blk) ⇒ Object



1425
1426
1427
# File 'lib/flt/num.rb', line 1425

def math(*args, &blk)
  self.context.math(*args, &blk)
end

.nanObject

A floating-point NaN (not a number)



1404
1405
1406
# File 'lib/flt/num.rb', line 1404

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

.Num(*args) ⇒ Object

Num is the general constructor that can be invoked on specific Flt::Num-derived classes.



1626
1627
1628
1629
1630
1631
1632
# File 'lib/flt/num.rb', line 1626

def Num(*args)
  if args.size==1 && args.first.instance_of?(self)
    args.first
  else
    new(*args)
  end
end

.num_classObject



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

def num_class
  self
end

.one_halfObject

One half: 1/2



1409
1410
1411
# File 'lib/flt/num.rb', line 1409

def one_half
  new '0.5'
end

.set_context(*args) ⇒ Object

Modify the current context, e.g. DecNum.set_context(:precision=>10)



1344
1345
1346
# File 'lib/flt/num.rb', line 1344

def self.set_context(*args)
  self.context = define_context(*args)
end

.zero(sign = +1) ⇒ Object

A floating-point number with value zero and the specified sign



1394
1395
1396
# File 'lib/flt/num.rb', line 1394

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

Instance Method Details

#%(other, context = nil) ⇒ Object

Modulo of two decimal numbers



1779
1780
1781
# File 'lib/flt/num.rb', line 1779

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

#*(other, context = nil) ⇒ Object

Multiplication of two decimal numbers



1769
1770
1771
# File 'lib/flt/num.rb', line 1769

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

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

Power



1784
1785
1786
# File 'lib/flt/num.rb', line 1784

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

#+(other, context = nil) ⇒ Object

Addition of two decimal numbers



1759
1760
1761
# File 'lib/flt/num.rb', line 1759

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

#+@(context = nil) ⇒ Object

Unary plus operator



1753
1754
1755
1756
# File 'lib/flt/num.rb', line 1753

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

#-(other, context = nil) ⇒ Object

Subtraction of two decimal numbers



1764
1765
1766
# File 'lib/flt/num.rb', line 1764

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

#-@(context = nil) ⇒ Object

Unary minus operator



1747
1748
1749
1750
# File 'lib/flt/num.rb', line 1747

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

#/(other, context = nil) ⇒ Object

Division of two decimal numbers



1774
1775
1776
# File 'lib/flt/num.rb', line 1774

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

#<(other) ⇒ Object



2811
2812
2813
# File 'lib/flt/num.rb', line 2811

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

#<=(other) ⇒ Object

For MRI this is unnecesary, but it is needed for Rubinius because of the coercion done in Numeric#< etc.



2808
2809
2810
# File 'lib/flt/num.rb', line 2808

def <=(other)
  (self<=>other) <= 0
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.



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
# File 'lib/flt/num.rb', line 2750

def <=>(other)
  case other
  when *num_class.context.coercible_types_or_num
    other = Num(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 *= num_class.int_radix_power(d)
          else
            other_padded *= num_class.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



2803
2804
2805
# File 'lib/flt/num.rb', line 2803

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

#>(other) ⇒ Object



2817
2818
2819
# File 'lib/flt/num.rb', line 2817

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

#>=(other) ⇒ Object



2814
2815
2816
# File 'lib/flt/num.rb', line 2814

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

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

Returns a copy with positive sign



3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
# File 'lib/flt/num.rb', line 3557

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.



3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
# File 'lib/flt/num.rb', line 3453

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



3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
# File 'lib/flt/num.rb', line 3573

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

  if special?
    if nan?
      return _fix_nan(context)
    else
      return Num(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 Num(sign,0,new_exp)
    else
      return Num(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 = Num(sign,1,exp_min-1)
      dg = number_of_digits # dig = 0
    else
      d = Num(self)
    end
    changed = d._round(context.rounding, dg)
    coeff = num_class.int_div_radix_power(d.coefficient, dg)
    coeff += 1 if changed==1
    ans = Num(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 = Num(ans.sign, num_class.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 = num_class.int_mult_radix_power(@coeff, @exp-etop)
    return Num(sign,self_padded,etop)
  end

  return Num(self)

end

#_fix_nan(context) ⇒ Object

adjust payload of a NaN to the context



3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
# File 'lib/flt/num.rb', line 3656

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 num_class.Num([@sign, payload, @exp])
    end
  end
  Num(self)
end

#_neg(context = nil) ⇒ Object

Returns copy with sign inverted



3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
# File 'lib/flt/num.rb', line 3527

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 = define_context(context)
  ans._fix(context)
end

#_pos(context = nil) ⇒ Object

Returns a copy with precision adjusted



3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
# File 'lib/flt/num.rb', line 3542

def _pos(context=nil)
  if special?
    ans = _check_nans(context)
    return ans if ans
  end
  if zero?
    ans = copy_abs
  else
    ans = Num(self)
  end
  context = 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



3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
# File 'lib/flt/num.rb', line 3476

def _rescale(exp, rounding)

  return Num(self) if special?
  return Num(sign, 0, exp) if zero?
  return Num(sign, @coeff*num_class.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 = Num(sign, 1, exp-1)
    nd = number_of_digits
  else
    slf = num_class.new(self)
  end

  changed = slf._round(rounding, nd)
  coeff = num_class.int_div_radix_power(@coeff, nd)
  coeff += 1 if changed==1
  Num(slf.sign, coeff, exp)

end

#_watched_rescale(exp, context, watch_exp) ⇒ Object



3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
# File 'lib/flt/num.rb', line 3497

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 Num(@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



2024
2025
2026
2027
2028
2029
2030
# File 'lib/flt/num.rb', line 2024

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



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
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
# File 'lib/flt/num.rb', line 1789

def add(other, context=nil)

  context = 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 Num(self)
    end

    return Num(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 = Num([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 = Num(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 Num(result_sign, result_coeff, result_exp)._fix(context)

end

#adjusted_exponentObject

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



2847
2848
2849
2850
2851
2852
2853
# File 'lib/flt/num.rb', line 2847

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 Flt::Num#round()



3143
3144
3145
3146
# File 'lib/flt/num.rb', line 3143

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

#coefficientObject

Significand as an integer, unsigned



2893
2894
2895
# File 'lib/flt/num.rb', line 2893

def coefficient
  @coeff
end

#coerce(other) ⇒ Object

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



1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
# File 'lib/flt/num.rb', line 1722

def coerce(other)
  case other
    when *num_class.context.coercible_types_or_num
      [Num(other),self]
    when Float
      [other, self.to_f]
    else
      super
  end
end

#compare(other, context = nil) ⇒ Object

Compares like <=> but returns a Num value.



2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
# File 'lib/flt/num.rb', line 2833

def compare(other, context=nil)

  other = _convert(other)

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

  return Num(self <=> other)

end

#convert_to(type, context = nil) ⇒ Object

Convert to other numerical type.



2635
2636
2637
2638
# File 'lib/flt/num.rb', line 2635

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

#copy_absObject

Returns a copy of with the sign set to +



2927
2928
2929
# File 'lib/flt/num.rb', line 2927

def copy_abs
  Num(+1,@coeff,@exp)
end

#copy_negateObject

Returns a copy of with the sign inverted



2932
2933
2934
# File 'lib/flt/num.rb', line 2932

def copy_negate
  Num(-@sign,@coeff,@exp)
end

#copy_sign(other) ⇒ Object

Returns a copy of with the sign of other



2937
2938
2939
2940
# File 'lib/flt/num.rb', line 2937

def copy_sign(other)
  sign = other.respond_to?(:sign) ? other.sign : ((other < 0) ? -1 : +1)
  Num(sign, @coeff, @exp)
end

#digitsObject

Digits of the significand as an array of integers



2872
2873
2874
# File 'lib/flt/num.rb', line 2872

def digits
  @coeff.to_s(num_class.radix).split('').map{|d| d.to_i} # TODO: optimize in derivided classes
end

#div(other, context = nil) ⇒ Object

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



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/flt/num.rb', line 2236

def div(other, context=nil)
  context = 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 num_class.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



1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
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
# File 'lib/flt/num.rb', line 1898

def divide(other, context=nil)
  context = 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 num_class.infinity(resultsign)
    end
    if other.infinite?
      context.exception(Clamped,"Division by infinity")
      return num_class.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
    shift = other.number_of_digits - self.number_of_digits + prec
    shift += 1
    exp = self.exponent - other.exponent - shift
    if shift >= 0
      coeff, remainder = (self.coefficient*num_class.int_radix_power(shift)).divmod(other.coefficient)
    else
      coeff, remainder = self.coefficient.divmod(other.coefficient*num_class.int_radix_power(-shift))
    end
    if remainder != 0
      return context.exception(Inexact) if context.exact?
      # result is not exact; adjust to ensure correct rounding
      if num_class.radix == 10
        # perform 05up rounding so the the final rounding will be correct
        coeff += 1 if (coeff%5) == 0
      else
        # since we will round to less digits and there is a remainder, we just need
        # to append some nonzero digit; but we must avoid producing a tie (adding a single
        # digit whose value is radix/2), so we append two digits, 01, that will be rounded away
        coeff = num_class.int_mult_radix_power(coeff, 2) + 1
        exp -= 2
      end
    else
      # result is exact; get as close to idaal exponent as possible
      ideal_exp = self.exponent - other.exponent
      while (exp < ideal_exp) && ((coeff % num_class.radix)==0)
        coeff /= num_class.radix
        exp += 1
      end
    end

  end
  return Num(resultsign, coeff, exp)._fix(context)

end

#divide_int(other, context = nil) ⇒ Object

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



2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
# File 'lib/flt/num.rb', line 2211

def divide_int(other, context=nil)
  context = 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 num_class.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



2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
# File 'lib/flt/num.rb', line 2177

def divmod(other, context=nil)
  context = 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 [num_class.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


2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
# File 'lib/flt/num.rb', line 2144

def divrem(other, context=nil)
  context = 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 [num_class.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)


2827
2828
2829
2830
# File 'lib/flt/num.rb', line 2827

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

#even?Boolean

returns true if is an even integer

Returns:

  • (Boolean)


2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
# File 'lib/flt/num.rb', line 2961

def even?
  # integral? && ((to_i%2)==0)
  if finite?
    if @exp>0 || @coeff==0
      true
    else
      if @exp <= -number_of_digits
        false
      else
        m = num_class.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



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
# File 'lib/flt/num.rb', line 2480

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

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

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

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

  # exp(Infinity) = Infinity
  return Num(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

  if self.sign == +1 and adj > _number_of_digits((context.emax+1)*3)
    # overflow
    ans = Num(+1, 1, context.emax+1)
  elsif self.sign == -1 and adj > _number_of_digits((-context.etiny+1)*3)
    # underflow to 0
    ans = Num(+1, 1, context.etiny-1)
  elsif self.sign == +1 and adj < -p
    # p+1 digits; final round will raise correct flags
    ans = Num(+1, num_clas.int_radix_power(p)+1, -p)
  elsif self.sign == -1 and adj < -p-1
    # p+1 digits; final round will raise correct flags
    ans = Num(+1, num_clas.int_radix_power(p+1)-1, -p-1)
  else
    # general case
    x_sign = self.sign
    x = self.copy_sign(+1)
    i, lasts, s, fact, num = 0, 0, 1, 1, 1
    elim = [context.emax, -context.emin, 10000].max
    xprec = num_class.radix==10 ? 3 : 4
    num_class.local_context(context, :extra_precision=>xprec, :rounding=>:half_even, :elimit=>elim) do
      while s != lasts
        lasts = s
        i += 1
        fact *= i
        num *= x
        s += num / fact
      end
      s = num_class.Num(1)/s if x_sign<0
    end
    ans = s
  end

  # at this stage, ans should round correctly with *any*
  # rounding mode, not just with ROUND_HALF_EVEN
  num_class.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.



2898
2899
2900
# File 'lib/flt/num.rb', line 2898

def exponent
  @exp
end

#finite?Boolean

Returns whether the number is finite

Returns:

  • (Boolean)


1670
1671
1672
# File 'lib/flt/num.rb', line 1670

def finite?
  !special?
end

#floor(opt = {}) ⇒ Object

General floor operation (as for Float) with same options for precision as Flt::Num#round()



3150
3151
3152
3153
# File 'lib/flt/num.rb', line 3150

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.



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/flt/num.rb', line 3165

def fma(other, third, context=nil)
  context =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 = num_class.infinity(self.sign*other.sign)
    elsif other.infinite?
      return context.exception(InvalidOperation, '0 * INF  in fma') if self.zero?
      product = num_class.infinity(self.sign*other.sign)
    end
  else
    product = Num(self.sign*other.sign,self.coefficient*other.coefficient, self.exponent+other.exponent)
  end
  return product.add(third, context)
end

#fraction_partObject

Fraction part (as a Num)



2911
2912
2913
2914
2915
# File 'lib/flt/num.rb', line 2911

def fraction_part
  ans = _check_nans
  return ans if ans
  self - self.integer_part
end

#fractional_exponentObject

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



2861
2862
2863
# File 'lib/flt/num.rb', line 2861

def fractional_exponent
  scientific_exponent + 1
end

#hashObject



2823
2824
2825
# File 'lib/flt/num.rb', line 2823

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

#infinite?Boolean

Returns whether the number is infinite

Returns:

  • (Boolean)


1665
1666
1667
# File 'lib/flt/num.rb', line 1665

def infinite?
  @exp == :inf
end

#inspectObject



2739
2740
2741
2742
2743
2744
2745
2746
# File 'lib/flt/num.rb', line 2739

def inspect
  class_name = num_class.to_s.split('::').last
  if $DEBUG
    "#{class_name}('#{self}') [coeff:#{@coeff.inspect} exp:#{@exp.inspect} s:#{@sign.inspect} radix:#{num_class.radix}]"
  else
    "#{class_name}('#{self}')"
  end
end

#integer_partObject

Integer part (as a Num)



2903
2904
2905
2906
2907
2908
# File 'lib/flt/num.rb', line 2903

def integer_part
  ans = _check_nans
  return ans if ans
  return_as_num = {:places=>0}
  self.sign < 0 ? self.ceil(return_as_num) : self.floor(return_as_num)
end

#integral?Boolean

Returns true if the value is an integer

Returns:

  • (Boolean)


2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
# File 'lib/flt/num.rb', line 2943

def integral?
  if finite?
    if @exp>=0 || @coeff==0
      true
    else
      if @exp <= -number_of_digits
        false
      else
        m = num_class.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



2882
2883
2884
2885
# File 'lib/flt/num.rb', line 2882

def integral_exponent
  # fractional_exponent - number_of_digits
  @exp
end

#integral_significandObject

Significand as an integer, unsigned. Synonym of coefficient



2877
2878
2879
# File 'lib/flt/num.rb', line 2877

def integral_significand
  @coeff
end

#ln(context = nil) ⇒ Object

Returns the natural (base e) logarithm



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
2602
2603
2604
2605
2606
# File 'lib/flt/num.rb', line 2547

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

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

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

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

  # ln(1.0) == 0.0
  return num_class.zero if self == Num(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?

  elim = [context.emax, -context.emin, 10000].max
  xprec = num_class.radix==10 ? 3 : 4
  num_class.local_context(context, :extra_precision=>xprec, :rounding=>:half_even, :elimit=>elim) do

    one = num_class.Num(1)

    x = self
    if (expo = x.adjusted_exponent)<-1 || expo>=2
      x = x.scaleb(-expo)
    else
      expo = nil
    end

    x = (x-one)/(x+one)
    x2 = x*x
    ans = x
    d = ans
    i = one
    last_ans = nil
    while ans != last_ans
      last_ans = ans
      x = x2*x
      i += 2
      d = x/i
      ans += d
    end
    ans *= 2
    if expo
      ans += num_class.Num(num_class.radix).ln*expo
    end
  end

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

#log(b = nil, context = nil) ⇒ Object

Ruby-style logarithm of arbitrary base, e (natural base) by default



2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
# File 'lib/flt/num.rb', line 2609

def log(b=nil, context=nil)
  if b.nil?
    self.ln(context)
  elsif b==10
    self.log10(context)
  elsif b==2
    self.log2(context)
  else
    context = num_class.define_context(context)
    +num_class.context(:extra_precision=>3){self.ln(context)/num_class[b].ln(context)}
  end
end

#log10(context = nil) ⇒ Object

Returns the base 10 logarithm



2623
2624
2625
2626
# File 'lib/flt/num.rb', line 2623

def log10(context=nil)
  context = num_class.define_context(context)
  num_class.context(:extra_precision=>3){self.ln/num_class.Num(10).ln}
end

#log2(context = nil) ⇒ Object

Returns the base 2 logarithm



2629
2630
2631
2632
# File 'lib/flt/num.rb', line 2629

def log2(context=nil)
  context = num_class.define_context(context)
  num_class.context(context, :extra_precision=>3){self.ln()/num_class.Num(2).ln}
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).



2448
2449
2450
2451
2452
2453
2454
2455
# File 'lib/flt/num.rb', line 2448

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

#minus(context = nil) ⇒ Object

Unary prefix minus operator



2038
2039
2040
# File 'lib/flt/num.rb', line 2038

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

#modulo(other, context = nil) ⇒ Object

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



2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
# File 'lib/flt/num.rb', line 2262

def modulo(other, context=nil)
  context = 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



1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
# File 'lib/flt/num.rb', line 1869

def multiply(other, context=nil)
  context = 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 num_class.infinity(resultsign)
    end
    if other.infinite?
      return context.exception(InvalidOperation,"0 * (+-)INF") if self.zero?
      return num_class.infinity(resultsign)
    end
  end

  resultexp = self.exponent + other.exponent

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

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


1650
1651
1652
# File 'lib/flt/num.rb', line 1650

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

#next_minus(context = nil) ⇒ Object

Largest representable number smaller than itself



2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
# File 'lib/flt/num.rb', line 2043

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

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

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

#next_plus(context = nil) ⇒ Object

Smallest representable number larger than itself



2074
2075
2076
2077
2078
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
# File 'lib/flt/num.rb', line 2074

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

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

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

  result = nil
  num_class.local_context(context) do |local|
    local.rounding = :ceiling
    local.ignore_all_flags
    result = self._fix(local)
    if result == self
      result = self + Num(+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.



2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
# File 'lib/flt/num.rb', line 2107

def next_toward(other, context=nil)
  context = 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)


1680
1681
1682
# File 'lib/flt/num.rb', line 1680

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

#normal?(context = nil) ⇒ Boolean

Returns whether the number is normal

Returns:

  • (Boolean)


1692
1693
1694
1695
1696
# File 'lib/flt/num.rb', line 1692

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

#normalize(context = nil) ⇒ Object

Normalizes (changes quantum) so that the coefficient has precision digits, unless it is subnormal. For surnormal numbers the Subnormal flag is raised an a subnormal is returned with the smallest possible exponent.

This is different from reduce GDAS function which was formerly called normalize, and corresponds to the classic meaning of floating-point normalization.

Note that the number is also rounded (precision is reduced) if it had more precision than the context.



2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
# File 'lib/flt/num.rb', line 2422

def normalize(context=nil)
  context = define_context(context)
  return Num(self) if self.special? || self.zero? || context.exact?
  sign, coeff, exp = self._fix(context).split
  if self.subnormal?
    context.exception Subnormal
    if exp > context.etiny
      coeff = num_class.int_mult_radix_power(coeff, exp - context.etiny)
      exp = context.etiny
    end
  else
    min_normal_coeff = context.minimum_normalized_coefficient
    while coeff < min_normal_coeff
      coeff = num_class.int_mult_radix_power(coeff, 1)
      exp -= 1
    end
  end
  Num(sign, coeff, exp)
end

#num_classObject



1382
1383
1384
# File 'lib/flt/num.rb', line 1382

def num_class
  self.class
end

#number_class(context = nil) ⇒ Object

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

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


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

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



2866
2867
2868
2869
# File 'lib/flt/num.rb', line 2866

def number_of_digits
  # digits.size
  @coeff.is_a?(Integer) ? @coeff.to_s(num_class.radix).size : 0
end

#odd?Boolean

returns true if is an odd integer

Returns:

  • (Boolean)


2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
# File 'lib/flt/num.rb', line 2985

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 = num_class.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



2033
2034
2035
# File 'lib/flt/num.rb', line 2033

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 may be computed more efficiently. It is always exact.



3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
# File 'lib/flt/num.rb', line 3269

def power(other, modulo=nil, context=nil)
  if context.nil? && (modulo.kind_of?(ContextBase) || modulo.is_a?(Hash))
    context = modulo
    modulo = nil
  end

  context = num_class.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 Num(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) ? Num(result_sign, 0, 0) : num_class.infinity(result_sign)
  end

  # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
  if _self.infinite?
    return (other.sign == +1) ? num_class.infinity(result_sign) : Num(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 == Num(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 Num(result_sign, num_class.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 Num(result_sign, 0, 0)
    else
      return num_class.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
  # log_radix(self)*other >= radix**bound and bound >= len(str(Emax))
  # then radixs**bound >= radix**len(str(Emax)) >= Emax+1 and hence
  # self**other >= radix**(Emax+1), so overflow occurs.  The test
  # for underflow is similar.
  bound = _self._log_radix_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 >= _number_of_digits(context.emax)
      ans = Num(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 >= _number_of_digits(-etiny)
      ans = Num(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 # ???? 4 ? ...
        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 = Num(-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 = _power(xc, xe, yc, ye, p+extra)
      break if (coeff % (num_class.int_radix_power(_number_of_digits(coeff)-p)/2)) != 0 # base 2: (coeff % (10**(_number_of_digits(coeff)-p-1))) != 0
      extra += 3
    end
    ans = Num(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 = Num(ans.sign, num_class.int_mult_radix_power(ans.coefficient, expdiff), ans.exponent-expdiff)
    end
    context.exception Underflow if ans.adjusted_exponent < context.emin
  end

  ans = ans % modulo if modulo

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


1655
1656
1657
# File 'lib/flt/num.rb', line 1655

def qnan?
  @exp == :nan
end

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

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



3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
# File 'lib/flt/num.rb', line 3028

def quantize(exp, context=nil, watch_exp=true)
  exp = _convert(exp)
  context = define_context(context)
  if self.special? || exp.special?
    ans = _check_nans(context, exp)
    return ans if ans
    if exp.infinite? || self.infinite?
      return Num(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

#rationalize(tol = nil) ⇒ Object

Approximate conversion to Rational within given tolerance



2673
2674
2675
2676
2677
2678
2679
2680
2681
# File 'lib/flt/num.rb', line 2673

def rationalize(tol=nil)
  tol ||= Flt.Tolerance(Rational(1,2),:ulps)
  case tol
  when Integer
    Rational(*Support::Rationalizer.max_denominator(self, tol, num_class))
  else
    Rational(*Support::Rationalizer[tol].rationalize(self))
  end
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)



2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
# File 'lib/flt/num.rb', line 2373

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

  return Num(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 Num(dup.sign, coeff/num_class.int_radix_power(nd-end_d), exp)
end

#reduced_exponentObject

Exponent corresponding to the integral significand with all trailing digits removed. Does not use any context; equals the value of self.reduce.exponent (but as an integer rather than a Num) except for special values and when the number is rounded under the context or exceeds its limits.



2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
# File 'lib/flt/num.rb', line 2399

def reduced_exponent
  if self.special? || self.zero?
    0
  else
    exp = self.exponent
    dgs = self.digits
    nd = dgs.size # self.number_of_digits
      while dgs[nd-1]==0
      exp += 1
      nd -= 1
    end
    exp
  end
end

#remainder(other, context = nil) ⇒ Object

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



2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
# File 'lib/flt/num.rb', line 2285

def remainder(other, context=nil)
  context = 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)


2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
# File 'lib/flt/num.rb', line 2309

def remainder_near(other, context=nil)
  context = 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 Num(self)._fix(context)
  end

  ideal_exp = [self.exponent, other.exponent].min
  if self.zero?
    return Num(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 = num_class.int_mult_radix_power(self_coeff, de)
    else
      other_coeff = num_class.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 >= num_class.int_radix_power(context.precision) && !context.exact?

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

  return Num(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.



3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
# File 'lib/flt/num.rb', line 3011

def rescale(exp, context=nil, watch_exp=true)
  context = 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 Num(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 Num.

  • :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
:rindex     7   6   5   4     3    2    1    0


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
# File 'lib/flt/num.rb', line 3112

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 - num_class.Num(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 = num_class.int_div_radix_power(@coeff, dg)
  exp = @exp + dg
  coeff += 1 if changed==1
  result = Num(@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)


3049
3050
3051
3052
3053
3054
3055
# File 'lib/flt/num.rb', line 3049

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.



2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
# File 'lib/flt/num.rb', line 2458

def scaleb(other, context=nil)

  context = 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 Num(self) if infinite?
  return Num(@sign, @coeff, @exp+i)._fix(context)

end

#scientific_exponentObject

Synonym for Num#adjusted_exponent()



2856
2857
2858
# File 'lib/flt/num.rb', line 2856

def scientific_exponent
  adjusted_exponent
end

#signObject

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



2888
2889
2890
# File 'lib/flt/num.rb', line 2888

def sign
  @sign
end

#snan?Boolean

Returns whether the number is a signaling NaN

Returns:

  • (Boolean)


1660
1661
1662
# File 'lib/flt/num.rb', line 1660

def snan?
  @exp == :snan
end

#special?Boolean

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

Returns:

  • (Boolean)


1645
1646
1647
# File 'lib/flt/num.rb', line 1645

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



1640
1641
1642
# File 'lib/flt/num.rb', line 1640

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

#sqrt(context = nil) ⇒ Object

Square root



1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
# File 'lib/flt/num.rb', line 1961

def sqrt(context=nil)
  context = define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    return Num(self) if infinite? && @sign==+1
  end
  return Num(@sign, 0, @exp/2)._fix(context) if zero?
  return context.exception(InvalidOperation, 'sqrt(-x), x>0') if @sign<0
  prec = context.precision + 1

  # express the number in radix**2 base
  e = (@exp >> 1)
  if (@exp & 1)!=0
    c = @coeff*num_class.radix
    l = (number_of_digits >> 1) + 1
  else
    c = @coeff
    l = (number_of_digits+1) >> 1
  end
  shift = prec - l
  if shift >= 0
    c = num_class.int_mult_radix_power(c, (shift<<1))
    exact = true
  else
    c, remainder = c.divmod(num_class.int_radix_power((-shift)<<1))
    exact = (remainder==0)
  end
  e -= shift

  n = num_class.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 = num_class.int_div_radix_power(n, shift)
    else
      n = num_class.int_mult_radix_power(n, -shift)
    end
    e += shift
  else
    return context.exception(Inexact) if context.exact?
    # result is not exact; adjust to ensure correct rounding
    if num_class.radix == 10
      n += 1 if (n%5)==0
    else
      n = num_class.int_mult_radix_power(n, 2) + 1
      e -= 2
    end
  end
  ans = Num(+1,n,e)
  num_class.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)


1685
1686
1687
1688
1689
# File 'lib/flt/num.rb', line 1685

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

#subtract(other, context = nil) ⇒ Object

Subtraction



1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
# File 'lib/flt/num.rb', line 1856

def subtract(other, context=nil)

  context = 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



2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
# File 'lib/flt/num.rb', line 2684

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*(num_class.radix.to_f**@exp)).to_f
  end
end

#to_iObject

Ruby-style to integer conversion.



2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
# File 'lib/flt/num.rb', line 2641

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

#to_int_scaleObject

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



2918
2919
2920
2921
2922
2923
2924
# File 'lib/flt/num.rb', line 2918

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.



3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
# File 'lib/flt/num.rb', line 3058

def to_integral_exact(context=nil)
  context = define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    return Num(self)
  end
  return Num(self) if @exp >= 0
  return Num(@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.



3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
# File 'lib/flt/num.rb', line 3074

def to_integral_value(context=nil)
  context = define_context(context)
  if special?
    ans = _check_nans(context)
    return ans if ans
    return Num(self)
  end
  return Num(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



2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
# File 'lib/flt/num.rb', line 2659

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, num_class.int_radix_power(-@exp))
    else
      Rational(num_class.int_mult_radix_power(@sign*@coeff,@exp), 1)
    end
  end
end

#to_s(*args) ⇒ Object

Convert to a text literal in the specified base (10 by default).

If the output base is the floating-point radix, the rendered value is the exact value of the number, showing trailing zeros up to the stored precision.

With bases different from the radix, the floating-point number is treated as an approximation with a precision of number_of_digits, representing any value within its rounding range. In that case, this method always renders that aproximated value in other base without introducing additional precision.

The resulting text numeral is such that it has as few digits as possible while preserving the original while if converted back to the same type of floating-point value with the same context precision that the original number had (number_of_digits).

To render the exact value of a Num x in a different base b this can be used

Flt::Num.convert_exact(x, b).to_s(:base=>b)

Or, to represent a BinNum x in decimal:

x.to_decimal_exact(:exact=>true).to_s

Options: :base output base, 10 by default

:rounding is used to override the context rounding, but it’s main use is specify :nearest as the rounding-mode, which means that the text literal will have enough digits to be converted back to self in any round-to_nearest rounding mode. Otherwise only enough digits for conversion in a specific rounding mode are produced.

:all_digits if true all significant digits are shown. A digit is considered as significant here if when used on input, cannot arbitrarily change its value and preserve the parsed value of the floating point number. Using all_digits will show trailing zeros up to the precision of the floating-point, so the output will preserve the input precision. With all_digits and the :down rounding-mod (truncation), the result will be the exact value floating-point value in the output base (if it is conmensurable with the floating-point base).

Raises:

  • (TypeError)


3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
# File 'lib/flt/num.rb', line 3224

def to_s(*args)
  eng=false
  context=nil

  # admit legacy arguments eng, context in that order
  if [true,false].include?(args.first)
    eng = args.shift
  end
  if args.first.is_a?(Num::ContextBase)
    context = args.shift
  end
  # admit also :eng to specify the eng mode
  if args.first == :eng
    eng = true
    args.shift
  end
  raise TypeError, "Invalid arguments to #{num_class}#to_s" if args.size>1 || (args.size==1 && !args.first.is_a?(Hash))
  # an admit arguments through a final parameters Hash
  options = args.first || {}
  context = options.delete(:context) if options.has_key?(:context)
  eng = options.delete(:eng) if options.has_key?(:eng)

  format(context, options.merge(:eng=>eng))
end

#truncate(opt = {}) ⇒ Object

General truncate operation (as for Float) with same options for precision as Flt::Num#round()



3157
3158
3159
3160
# File 'lib/flt/num.rb', line 3157

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

#ulp(context = nil, mode = :low) ⇒ 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 If the mode parameter has the value :high the Golberg ulp is computed instead; which is different on the powers of the radix (which are the borders between areas of different ulp-magnitude)



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
# File 'lib/flt/num.rb', line 2703

def ulp(context = nil, mode=:low)
  context = define_context(context)

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

  if self.nan?
    return Num(self)
  elsif self.infinite?
    # The ulp here is context.maximum_finite - context.maximum_finite.next_minus
    return Num(+1, 1, context.etop)
  elsif self.zero? || self.adjusted_exponent <= context.emin
    # This is the ulp value for self.abs <= context.minimum_normal*num_class.context
    # Here we use it for self.abs < context.minimum_normal*num_class.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*num_class.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 (so ulp varies with adjusted_exponent).
    # The next line selects the smaller ulp for powers of the radix:
    exp -= 1 if sig == num_class.int_radix_power(context.precision-1) if mode == :low

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

#zero?Boolean

Returns whether the number is zero

Returns:

  • (Boolean)


1675
1676
1677
# File 'lib/flt/num.rb', line 1675

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