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

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

FlagValues, adjust_digits, simplified_round_mode

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.



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
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
# File 'lib/flt/num.rb', line 1486

def initialize(*args)
  options = args.pop if args.last.is_a?(Hash)
  options ||= {}
  context = args.pop if args.size > 0 && (args.last.kind_of?(ContextBase) || args.last.nil?)
  context ||= 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.empty?
    args = [options.delete(:sign)||+1,
            options.delete(:coefficient) || 0,
            options.delete(:exponent) || 0]
  end
  mode ||= options.delete(:mode)
  base = options.delete(:base)
  context = options if context.nil? && !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)


4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
# File 'lib/flt/num.rb', line 4701

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



1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/flt/num.rb', line 1279

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



1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
# File 'lib/flt/num.rb', line 1333

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



1353
1354
1355
# File 'lib/flt/num.rb', line 1353

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



1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/flt/num.rb', line 1313

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



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

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

.int_div_radix_power(x, n) ⇒ Object



1435
1436
1437
# File 'lib/flt/num.rb', line 1435

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



1431
1432
1433
# File 'lib/flt/num.rb', line 1431

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

.int_radix_power(n) ⇒ Object



1427
1428
1429
# File 'lib/flt/num.rb', line 1427

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.



1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
# File 'lib/flt/num.rb', line 1366

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



1439
1440
1441
# File 'lib/flt/num.rb', line 1439

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

.nanObject

A floating-point NaN (not a number)



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

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.



1641
1642
1643
1644
1645
1646
1647
# File 'lib/flt/num.rb', line 1641

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

.num_classObject



1401
1402
1403
# File 'lib/flt/num.rb', line 1401

def num_class
  self
end

.one_halfObject

One half: 1/2



1423
1424
1425
# File 'lib/flt/num.rb', line 1423

def one_half
  new '0.5'
end

.set_context(*args) ⇒ Object

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



1358
1359
1360
# File 'lib/flt/num.rb', line 1358

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



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

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

Instance Method Details

#%(other, context = nil) ⇒ Object

Modulo of two decimal numbers



1794
1795
1796
# File 'lib/flt/num.rb', line 1794

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

#*(other, context = nil) ⇒ Object

Multiplication of two decimal numbers



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

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

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

Power



1799
1800
1801
# File 'lib/flt/num.rb', line 1799

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

#+(other, context = nil) ⇒ Object

Addition of two decimal numbers



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

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

#+@(context = nil) ⇒ Object

Unary plus operator



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

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

#-(other, context = nil) ⇒ Object

Subtraction of two decimal numbers



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

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

#-@(context = nil) ⇒ Object

Unary minus operator



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

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

#/(other, context = nil) ⇒ Object

Division of two decimal numbers



1789
1790
1791
# File 'lib/flt/num.rb', line 1789

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

#<(other) ⇒ Object



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

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.



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

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.



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

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



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

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

#>(other) ⇒ Object



2832
2833
2834
# File 'lib/flt/num.rb', line 2832

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

#>=(other) ⇒ Object



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

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

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

Returns a copy with positive sign



3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
# File 'lib/flt/num.rb', line 3517

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.



3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
# File 'lib/flt/num.rb', line 3413

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.



3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
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
# File 'lib/flt/num.rb', line 3533

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.normalized?
    exp = @exp
    coeff = @coeff
    if self_is_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
    if exp != @exp || coeff != @coeff
      return Num(@sign, coeff, exp)
    end
  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



3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
# File 'lib/flt/num.rb', line 3635

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



3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
# File 'lib/flt/num.rb', line 3487

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



3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
# File 'lib/flt/num.rb', line 3502

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



3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
# File 'lib/flt/num.rb', line 3436

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



3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
# File 'lib/flt/num.rb', line 3457

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



2039
2040
2041
2042
2043
2044
2045
# File 'lib/flt/num.rb', line 2039

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



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
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
# File 'lib/flt/num.rb', line 1804

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



2862
2863
2864
2865
2866
2867
2868
# File 'lib/flt/num.rb', line 2862

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



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

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

#coefficientObject

Significand as an integer, unsigned



2908
2909
2910
# File 'lib/flt/num.rb', line 2908

def coefficient
  @coeff
end

#coerce(other) ⇒ Object

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



1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
# File 'lib/flt/num.rb', line 1737

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.



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

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.



2650
2651
2652
2653
# File 'lib/flt/num.rb', line 2650

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 +



2942
2943
2944
# File 'lib/flt/num.rb', line 2942

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

#copy_negateObject

Returns a copy of with the sign inverted



2947
2948
2949
# File 'lib/flt/num.rb', line 2947

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

#copy_sign(other) ⇒ Object

Returns a copy of with the sign of other



2952
2953
2954
2955
# File 'lib/flt/num.rb', line 2952

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



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

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



2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
# File 'lib/flt/num.rb', line 2251

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



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
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
# File 'lib/flt/num.rb', line 1913

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



2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
# File 'lib/flt/num.rb', line 2226

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



2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
# File 'lib/flt/num.rb', line 2192

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


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

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)


2842
2843
2844
2845
# File 'lib/flt/num.rb', line 2842

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)


2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
# File 'lib/flt/num.rb', line 2976

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



2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
# File 'lib/flt/num.rb', line 2495

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.



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

def exponent
  @exp
end

#finite?Boolean

Returns whether the number is finite

Returns:

  • (Boolean)


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

def finite?
  !special?
end

#floor(opt = {}) ⇒ Object

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



3165
3166
3167
3168
# File 'lib/flt/num.rb', line 3165

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.



3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
# File 'lib/flt/num.rb', line 3180

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)



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

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)



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

def fractional_exponent
  scientific_exponent + 1
end

#hashObject



2838
2839
2840
# File 'lib/flt/num.rb', line 2838

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

#infinite?Boolean

Returns whether the number is infinite

Returns:

  • (Boolean)


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

def infinite?
  @exp == :inf
end

#inspectObject



2754
2755
2756
2757
2758
2759
2760
2761
# File 'lib/flt/num.rb', line 2754

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)



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

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)


2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
# File 'lib/flt/num.rb', line 2958

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



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

def integral_exponent
  # fractional_exponent - number_of_digits
  @exp
end

#integral_significandObject

Significand as an integer, unsigned. Synonym of coefficient



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

def integral_significand
  @coeff
end

#ln(context = nil) ⇒ Object

Returns the natural (base e) logarithm



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
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
# File 'lib/flt/num.rb', line 2562

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



2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
# File 'lib/flt/num.rb', line 2624

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



2638
2639
2640
2641
# File 'lib/flt/num.rb', line 2638

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



2644
2645
2646
2647
# File 'lib/flt/num.rb', line 2644

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



2463
2464
2465
2466
2467
2468
2469
2470
# File 'lib/flt/num.rb', line 2463

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



2053
2054
2055
# File 'lib/flt/num.rb', line 2053

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

#modulo(other, context = nil) ⇒ Object

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



2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
# File 'lib/flt/num.rb', line 2277

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



1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
# File 'lib/flt/num.rb', line 1884

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)


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

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

#next_minus(context = nil) ⇒ Object

Largest representable number smaller than itself



2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
# File 'lib/flt/num.rb', line 2058

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



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

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.



2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
# File 'lib/flt/num.rb', line 2122

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)


1695
1696
1697
# File 'lib/flt/num.rb', line 1695

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

#normal?(context = nil) ⇒ Boolean

Returns whether the number is normal

Returns:

  • (Boolean)


1707
1708
1709
1710
1711
# File 'lib/flt/num.rb', line 1707

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.



2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
# File 'lib/flt/num.rb', line 2437

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



1396
1397
1398
# File 'lib/flt/num.rb', line 1396

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'


1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
# File 'lib/flt/num.rb', line 1716

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



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

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)


3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
# File 'lib/flt/num.rb', line 3000

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



2048
2049
2050
# File 'lib/flt/num.rb', line 2048

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.



3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
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
# File 'lib/flt/num.rb', line 3229

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)


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

def qnan?
  @exp == :nan
end

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

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



3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
# File 'lib/flt/num.rb', line 3043

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



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

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)



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

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.



2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
# File 'lib/flt/num.rb', line 2414

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)



2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
# File 'lib/flt/num.rb', line 2300

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)


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
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
# File 'lib/flt/num.rb', line 2324

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.



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

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


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

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)


3064
3065
3066
3067
3068
3069
3070
# File 'lib/flt/num.rb', line 3064

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.



2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
# File 'lib/flt/num.rb', line 2473

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



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

def scientific_exponent
  adjusted_exponent
end

#signObject

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



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

def sign
  @sign
end

#snan?Boolean

Returns whether the number is a signaling NaN

Returns:

  • (Boolean)


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

def snan?
  @exp == :snan
end

#special?Boolean

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

Returns:

  • (Boolean)


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

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



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

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

#sqrt(context = nil) ⇒ Object

Square root



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
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
# File 'lib/flt/num.rb', line 1976

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)


1700
1701
1702
1703
1704
# File 'lib/flt/num.rb', line 1700

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



1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
# File 'lib/flt/num.rb', line 1871

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



2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
# File 'lib/flt/num.rb', line 2699

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.



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

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.



2933
2934
2935
2936
2937
2938
2939
# File 'lib/flt/num.rb', line 2933

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.



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

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.



3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
# File 'lib/flt/num.rb', line 3089

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



2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
# File 'lib/flt/num.rb', line 2674

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

Representation as text of a number: this is an alias of Num#format



3205
3206
3207
# File 'lib/flt/num.rb', line 3205

def to_s(*args)
  format *args
end

#truncate(opt = {}) ⇒ Object

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



3172
3173
3174
3175
# File 'lib/flt/num.rb', line 3172

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)



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

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)


1690
1691
1692
# File 'lib/flt/num.rb', line 1690

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