Class: Flt::Num
- Extended by:
- AuxiliarFunctions, Support
- Includes:
- Comparable, AuxiliarFunctions, Support::AuxiliarFunctions
- Defined in:
- lib/flt/num.rb,
lib/flt/complex.rb
Overview
ComplexContext
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
-
._base_coercible_types ⇒ Object
readonly
Returns the value of attribute _base_coercible_types.
-
._base_conversions ⇒ Object
readonly
Returns the value of attribute _base_conversions.
Class Method Summary collapse
- .[](*args) ⇒ Object
- .base_coercible_types ⇒ Object
- .base_conversions ⇒ Object
- .ccontext(*args) ⇒ Object
-
.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.
-
.context(*args, &blk) ⇒ Object
The current context (thread-local).
-
.context=(c) ⇒ Object
Change the current context (thread-local).
-
.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.
- .Flags(*values) ⇒ Object
-
.infinity(sign = +1) ⇒ Object
A floating-point infinite number with the specified sign.
- .int_div_radix_power(x, n) ⇒ Object
- .int_mult_radix_power(x, n) ⇒ Object
- .int_radix_power(n) ⇒ Object
-
.local_context(*args) ⇒ Object
Defines a scope with a local context.
- .math(*args, &blk) ⇒ Object
-
.nan ⇒ Object
A floating-point NaN (not a number).
-
.Num(*args) ⇒ Object
Num is the general constructor that can be invoked on specific Flt::Num-derived classes.
- .num_class ⇒ Object
-
.one_half ⇒ Object
One half: 1/2.
-
.set_context(*args) ⇒ Object
Modify the current context, e.g.
-
.zero(sign = +1) ⇒ Object
A floating-point number with value zero and the specified sign.
Instance Method Summary collapse
-
#%(other, context = nil) ⇒ Object
Modulo of two decimal numbers.
-
#*(other, context = nil) ⇒ Object
Multiplication of two decimal numbers.
-
#**(other, context = nil) ⇒ Object
Power.
-
#+(other, context = nil) ⇒ Object
Addition of two decimal numbers.
-
#+@(context = nil) ⇒ Object
Unary plus operator.
-
#-(other, context = nil) ⇒ Object
Subtraction of two decimal numbers.
-
#-@(context = nil) ⇒ Object
Unary minus operator.
-
#/(other, context = nil) ⇒ Object
Division of two decimal numbers.
-
#<=>(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.
- #==(other) ⇒ Object
-
#_abs(round = true, context = nil) ⇒ Object
Returns a copy with positive sign.
-
#_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.
-
#_fix(context) ⇒ Object
Round if it is necessary to keep within precision.
-
#_fix_nan(context) ⇒ Object
adjust payload of a NaN to the context.
-
#_neg(context = nil) ⇒ Object
Returns copy with sign inverted.
-
#_pos(context = nil) ⇒ Object
Returns a copy with precision adjusted.
-
#_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.
- #_watched_rescale(exp, context, watch_exp) ⇒ Object
-
#abs(context = nil) ⇒ Object
Absolute value.
-
#add(other, context = nil) ⇒ Object
Addition.
-
#adjusted_exponent ⇒ Object
Exponent of the magnitude of the most significant digit of the operand.
-
#ceil(opt = {}) ⇒ Object
General ceiling operation (as for Float) with same options for precision as Flt::Num#round().
-
#coefficient ⇒ Object
Significand as an integer, unsigned.
-
#coerce(other) ⇒ Object
Used internally to convert numbers to be used in an operation to a suitable numeric type.
-
#compare(other, context = nil) ⇒ Object
Compares like <=> but returns a Num value.
-
#convert_to(type, context = nil) ⇒ Object
Convert to other numerical type.
-
#copy_abs ⇒ Object
Returns a copy of with the sign set to +.
-
#copy_negate ⇒ Object
Returns a copy of with the sign inverted.
-
#copy_sign(other) ⇒ Object
Returns a copy of with the sign of other.
-
#digits ⇒ Object
Digits of the significand as an array of integers.
-
#div(other, context = nil) ⇒ Object
Ruby-style integer division: (x/y).floor.
-
#divide(other, context = nil) ⇒ Object
Division.
-
#divide_int(other, context = nil) ⇒ Object
General Decimal Arithmetic Specification integer division: (x/y).truncate.
-
#divmod(other, context = nil) ⇒ Object
Ruby-style integer division and modulo: (x/y).floor, x - y*(x/y).floor.
-
#divrem(other, context = nil) ⇒ Object
General Decimal Arithmetic Specification integer division and remainder: (x/y).truncate, x - y*(x/y).truncate.
- #eql?(other) ⇒ Boolean
-
#even? ⇒ Boolean
returns true if is an even integer.
-
#exp(context = nil) ⇒ Object
Exponential function.
-
#exponent ⇒ Object
Exponent of the significand as an integer.
-
#finite? ⇒ Boolean
Returns whether the number is finite.
-
#floor(opt = {}) ⇒ Object
General floor operation (as for Float) with same options for precision as Flt::Num#round().
-
#fma(other, third, context = nil) ⇒ Object
Fused multiply-add.
-
#fraction_part ⇒ Object
Fraction part (as a Num).
-
#fractional_exponent ⇒ Object
Exponent as though the significand were a fraction (the decimal point before its first digit).
- #hash ⇒ Object
-
#infinite? ⇒ Boolean
Returns whether the number is infinite.
-
#initialize(*args) ⇒ Num
constructor
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.
- #inspect ⇒ Object
-
#integer_part ⇒ Object
Integer part (as a Num).
-
#integral? ⇒ Boolean
Returns true if the value is an integer.
-
#integral_exponent ⇒ Object
Exponent of the significand as an integer.
-
#integral_significand ⇒ Object
Significand as an integer, unsigned.
-
#ln(context = nil) ⇒ Object
Returns the natural (base e) logarithm.
-
#log(b = nil, context = nil) ⇒ Object
Ruby-style logarithm of arbitrary base, e (natural base) by default.
-
#log10(context = nil) ⇒ Object
Returns the base 10 logarithm.
-
#log2(context = nil) ⇒ Object
Returns the base 2 logarithm.
-
#logb(context = nil) ⇒ Object
Returns the exponent of the magnitude of the most significant digit.
-
#minus(context = nil) ⇒ Object
Unary prefix minus operator.
-
#modulo(other, context = nil) ⇒ Object
Ruby-style modulo: x - y*div(x,y).
-
#multiply(other, context = nil) ⇒ Object
Multiplication.
-
#nan? ⇒ Boolean
Returns whether the number is not actualy one (NaN, not a number).
-
#next_minus(context = nil) ⇒ Object
Largest representable number smaller than itself.
-
#next_plus(context = nil) ⇒ Object
Smallest representable number larger than itself.
-
#next_toward(other, context = nil) ⇒ Object
Returns the number closest to self, in the direction towards other.
-
#nonzero? ⇒ Boolean
Returns whether the number not zero.
-
#normal?(context = nil) ⇒ Boolean
Returns whether the number is normal.
-
#normalize(context = nil) ⇒ Object
Normalizes (changes quantum) so that the coefficient has precision digits, unless it is subnormal.
- #num_class ⇒ Object
-
#number_class(context = nil) ⇒ Object
Classifies a number as one of ‘sNaN’, ‘NaN’, ‘-Infinity’, ‘-Normal’, ‘-Subnormal’, ‘-Zero’, ‘+Zero’, ‘+Subnormal’, ‘+Normal’, ‘+Infinity’.
-
#number_of_digits ⇒ Object
Number of digits in the significand.
-
#odd? ⇒ Boolean
returns true if is an odd integer.
-
#plus(context = nil) ⇒ Object
Unary prefix plus operator.
-
#power(other, modulo = nil, context = nil) ⇒ Object
Raises to the power of x, to modulo if given.
-
#qnan? ⇒ Boolean
Returns whether the number is a quite NaN (non-signaling).
-
#quantize(exp, context = nil, watch_exp = true) ⇒ Object
Quantize so its exponent is the same as that of y.
-
#reduce(context = nil) ⇒ Object
Reduces an operand to its simplest form by removing trailing 0s and incrementing the exponent.
-
#remainder(other, context = nil) ⇒ Object
General Decimal Arithmetic Specification remainder: x - y*divide_int(x,y).
-
#remainder_near(other, context = nil) ⇒ Object
General Decimal Arithmetic Specification remainder-near: x - y*round_half_even(x/y).
-
#rescale(exp, context = nil, watch_exp = true) ⇒ Object
Rescale so that the exponent is exp, either by padding with zeros or by truncating digits.
-
#round(opt = {}) ⇒ Object
General rounding.
-
#same_quantum?(other) ⇒ Boolean
Return true if has the same exponent as other.
-
#scaleb(other, context = nil) ⇒ Object
Adds a value to the exponent.
-
#scientific_exponent ⇒ Object
Synonym for Num#adjusted_exponent().
-
#sign ⇒ Object
Sign of the number: +1 for plus / -1 for minus.
-
#snan? ⇒ Boolean
Returns whether the number is a signaling NaN.
-
#special? ⇒ Boolean
Returns whether the number is a special value (NaN or Infinity).
-
#split ⇒ Object
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.
-
#sqrt(context = nil) ⇒ Object
Square root.
-
#subnormal?(context = nil) ⇒ Boolean
Returns whether the number is subnormal.
-
#subtract(other, context = nil) ⇒ Object
Subtraction.
-
#to_f ⇒ Object
Conversion to Float.
-
#to_i ⇒ Object
Ruby-style to integer conversion.
-
#to_int_scale ⇒ Object
Return the value of the number as an signed integer and a scale.
-
#to_integral_exact(context = nil) ⇒ Object
Rounds to a nearby integer.
-
#to_integral_value(context = nil) ⇒ Object
Rounds to a nearby integer.
-
#to_r ⇒ Object
Conversion to Rational.
-
#to_s(*args) ⇒ Object
Convert to a text literal in the specified base (10 by default).
-
#truncate(opt = {}) ⇒ Object
General truncate operation (as for Float) with same options for precision as Flt::Num#round().
-
#ulp(context = nil, mode = :low) ⇒ Object
ulp (unit in the last place) according to the definition proposed by J.M.
-
#zero? ⇒ Boolean
Returns whether the number is zero.
Methods included from Support
FlagValues, 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.
-
: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.
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 |
# File 'lib/flt/num.rb', line 1360 def initialize(*args) = args.pop if args.last.is_a?(Hash) context = args.pop if args.size>0 && (args.last.kind_of?(ContextBase) || args.last.nil?) context ||= && .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? && args = [.delete(:sign)||+1, .delete(:coefficient) || 0, .delete(:exponent) || 0] end mode ||= && .delete(:mode) base = ( && .delete(:base)) || 10 context = if context.nil? && && !.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) 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 exp = m.exp.to_i if fracpart coeff = (intpart+fracpart).to_i(base) exp -= fracpart.size else coeff = intpart.to_i(base) 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 [:free, :short].include?(mode) && base == num_class.radix # simple case, the job is already done 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_types ⇒ Object (readonly)
Returns the value of attribute _base_coercible_types.
142 143 144 |
# File 'lib/flt/num.rb', line 142 def _base_coercible_types @_base_coercible_types end |
._base_conversions ⇒ Object (readonly)
Returns the value of attribute _base_conversions.
143 144 145 |
# File 'lib/flt/num.rb', line 143 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')
4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 |
# File 'lib/flt/num.rb', line 4350 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 } = class <<cls;self;end .send :define_method, :radix do base end cls.const_set :Context, Class.new(Num::ContextBase) cls::Context.send :define_method, :initialize do |*| super(cls, *) 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_types ⇒ Object
144 145 146 |
# File 'lib/flt/num.rb', line 144 def base_coercible_types Num._base_coercible_types end |
.base_conversions ⇒ Object
147 148 149 |
# File 'lib/flt/num.rb', line 147 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
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 |
# File 'lib/flt/num.rb', line 1159 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 = nil elsif arg.instance_of?(Hash) base = self::DefaultContext = arg else raise TypeError,"invalid argument for #{num_class}.Context" end when 2 base = args.first = args.last else raise ArgumentError,"wrong number of arguments (#{args.size} for 0, 1 or 2)" end if .nil? || .empty? base else self::Context.new(base, ) 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().
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 |
# File 'lib/flt/num.rb', line 1213 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).
1233 1234 1235 |
# File 'lib/flt/num.rb', line 1233 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
1193 1194 1195 1196 1197 1198 1199 1200 1201 |
# File 'lib/flt/num.rb', line 1193 def self.define_context(*) context = .shift if .first.instance_of?(self::Context) if context && .empty? context else context ||= self.context self.Context(context, *) end end |
.Flags(*values) ⇒ Object
365 366 367 |
# File 'lib/flt/num.rb', line 365 def self.Flags(*values) Flt::Support::Flags(EXCEPTIONS,*values) end |
.infinity(sign = +1) ⇒ Object
A floating-point infinite number with the specified sign
1293 1294 1295 |
# File 'lib/flt/num.rb', line 1293 def infinity(sign=+1) new [sign, 0, :inf] end |
.int_div_radix_power(x, n) ⇒ Object
1315 1316 1317 |
# File 'lib/flt/num.rb', line 1315 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
1311 1312 1313 |
# File 'lib/flt/num.rb', line 1311 def int_mult_radix_power(x,n) n < 0 ? (x / self.radix**(-n)) : (x * self.radix**n) end |
.int_radix_power(n) ⇒ Object
1307 1308 1309 |
# File 'lib/flt/num.rb', line 1307 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.
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 |
# File 'lib/flt/num.rb', line 1246 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
1319 1320 1321 |
# File 'lib/flt/num.rb', line 1319 def math(*args, &blk) self.context.math(*args, &blk) end |
.nan ⇒ Object
A floating-point NaN (not a number)
1298 1299 1300 |
# File 'lib/flt/num.rb', line 1298 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.
1493 1494 1495 1496 1497 1498 1499 |
# File 'lib/flt/num.rb', line 1493 def Num(*args) if args.size==1 && args.first.instance_of?(self) args.first else new(*args) end end |
.num_class ⇒ Object
1281 1282 1283 |
# File 'lib/flt/num.rb', line 1281 def num_class self end |
.one_half ⇒ Object
One half: 1/2
1303 1304 1305 |
# File 'lib/flt/num.rb', line 1303 def one_half new '0.5' end |
.set_context(*args) ⇒ Object
Modify the current context, e.g. DecNum.set_context(:precision=>10)
1238 1239 1240 |
# File 'lib/flt/num.rb', line 1238 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
1288 1289 1290 |
# File 'lib/flt/num.rb', line 1288 def zero(sign=+1) new [sign, 0, 0] end |
Instance Method Details
#%(other, context = nil) ⇒ Object
Modulo of two decimal numbers
1646 1647 1648 |
# File 'lib/flt/num.rb', line 1646 def %(other, context=nil) _bin_op :%, :modulo, other, context end |
#*(other, context = nil) ⇒ Object
Multiplication of two decimal numbers
1636 1637 1638 |
# File 'lib/flt/num.rb', line 1636 def *(other, context=nil) _bin_op :*, :multiply, other, context end |
#**(other, context = nil) ⇒ Object
Power
1651 1652 1653 |
# File 'lib/flt/num.rb', line 1651 def **(other, context=nil) _bin_op :**, :power, other, context end |
#+(other, context = nil) ⇒ Object
Addition of two decimal numbers
1626 1627 1628 |
# File 'lib/flt/num.rb', line 1626 def +(other, context=nil) _bin_op :+, :add, other, context end |
#+@(context = nil) ⇒ Object
Unary plus operator
1620 1621 1622 1623 |
# File 'lib/flt/num.rb', line 1620 def +@(context=nil) #(context || num_class.context).plus(self) _pos(context) end |
#-(other, context = nil) ⇒ Object
Subtraction of two decimal numbers
1631 1632 1633 |
# File 'lib/flt/num.rb', line 1631 def -(other, context=nil) _bin_op :-, :subtract, other, context end |
#-@(context = nil) ⇒ Object
Unary minus operator
1614 1615 1616 1617 |
# File 'lib/flt/num.rb', line 1614 def -@(context=nil) #(context || num_class.context).minus(self) _neg(context) end |
#/(other, context = nil) ⇒ Object
Division of two decimal numbers
1641 1642 1643 |
# File 'lib/flt/num.rb', line 1641 def /(other, context=nil) _bin_op :/, :divide, other, context end |
#<=>(other) ⇒ Object
Internal comparison operator: returns -1 if the first number is less than the second, 0 if both are equal or +1 if the first is greater than the secong.
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 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 |
# File 'lib/flt/num.rb', line 2588 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
2641 2642 2643 |
# File 'lib/flt/num.rb', line 2641 def ==(other) (self<=>other) == 0 end |
#_abs(round = true, context = nil) ⇒ Object
Returns a copy with positive sign
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 |
# File 'lib/flt/num.rb', line 3380 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.
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 |
# File 'lib/flt/num.rb', line 3276 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.
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 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 |
# File 'lib/flt/num.rb', line 3396 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
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 |
# File 'lib/flt/num.rb', line 3479 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
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 |
# File 'lib/flt/num.rb', line 3350 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
3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 |
# File 'lib/flt/num.rb', line 3365 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
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 |
# File 'lib/flt/num.rb', line 3299 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
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 |
# File 'lib/flt/num.rb', line 3320 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
1891 1892 1893 1894 1895 1896 1897 |
# File 'lib/flt/num.rb', line 1891 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
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 |
# File 'lib/flt/num.rb', line 1656 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_exponent ⇒ Object
Exponent of the magnitude of the most significant digit of the operand
2670 2671 2672 2673 2674 2675 2676 |
# File 'lib/flt/num.rb', line 2670 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()
2966 2967 2968 2969 |
# File 'lib/flt/num.rb', line 2966 def ceil(opt={}) opt[:rounding] = :ceiling round opt end |
#coefficient ⇒ Object
Significand as an integer, unsigned
2716 2717 2718 |
# File 'lib/flt/num.rb', line 2716 def coefficient @coeff end |
#coerce(other) ⇒ Object
Used internally to convert numbers to be used in an operation to a suitable numeric type
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 |
# File 'lib/flt/num.rb', line 1589 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.
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 |
# File 'lib/flt/num.rb', line 2656 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.
2484 2485 2486 2487 |
# File 'lib/flt/num.rb', line 2484 def convert_to(type, context=nil) context = define_context(context) context.convert_to(type, self) end |
#copy_abs ⇒ Object
Returns a copy of with the sign set to +
2750 2751 2752 |
# File 'lib/flt/num.rb', line 2750 def copy_abs Num(+1,@coeff,@exp) end |
#copy_negate ⇒ Object
Returns a copy of with the sign inverted
2755 2756 2757 |
# File 'lib/flt/num.rb', line 2755 def copy_negate Num(-@sign,@coeff,@exp) end |
#copy_sign(other) ⇒ Object
Returns a copy of with the sign of other
2760 2761 2762 2763 |
# File 'lib/flt/num.rb', line 2760 def copy_sign(other) sign = other.respond_to?(:sign) ? other.sign : ((other < 0) ? -1 : +1) Num(sign, @coeff, @exp) end |
#digits ⇒ Object
Digits of the significand as an array of integers
2695 2696 2697 |
# File 'lib/flt/num.rb', line 2695 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
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 |
# File 'lib/flt/num.rb', line 2103 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
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 |
# File 'lib/flt/num.rb', line 1765 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
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 |
# File 'lib/flt/num.rb', line 2078 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
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 2072 2073 2074 |
# File 'lib/flt/num.rb', line 2044 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
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 |
# File 'lib/flt/num.rb', line 2011 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
2650 2651 2652 2653 |
# File 'lib/flt/num.rb', line 2650 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
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 |
# File 'lib/flt/num.rb', line 2784 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
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 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 |
# File 'lib/flt/num.rb', line 2329 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 |
#exponent ⇒ Object
Exponent of the significand as an integer.
2721 2722 2723 |
# File 'lib/flt/num.rb', line 2721 def exponent @exp end |
#finite? ⇒ Boolean
Returns whether the number is finite
1537 1538 1539 |
# File 'lib/flt/num.rb', line 1537 def finite? !special? end |
#floor(opt = {}) ⇒ Object
General floor operation (as for Float) with same options for precision as Flt::Num#round()
2973 2974 2975 2976 |
# File 'lib/flt/num.rb', line 2973 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.
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 |
# File 'lib/flt/num.rb', line 2988 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_part ⇒ Object
Fraction part (as a Num)
2734 2735 2736 2737 2738 |
# File 'lib/flt/num.rb', line 2734 def fraction_part ans = _check_nans return ans if ans self - self.integer_part end |
#fractional_exponent ⇒ Object
Exponent as though the significand were a fraction (the decimal point before its first digit)
2684 2685 2686 |
# File 'lib/flt/num.rb', line 2684 def fractional_exponent scientific_exponent + 1 end |
#hash ⇒ Object
2646 2647 2648 |
# File 'lib/flt/num.rb', line 2646 def hash ([num_class]+reduce.split).hash # TODO: optimize end |
#infinite? ⇒ Boolean
Returns whether the number is infinite
1532 1533 1534 |
# File 'lib/flt/num.rb', line 1532 def infinite? @exp == :inf end |
#inspect ⇒ Object
2577 2578 2579 2580 2581 2582 2583 2584 |
# File 'lib/flt/num.rb', line 2577 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_part ⇒ Object
Integer part (as a Num)
2726 2727 2728 2729 2730 2731 |
# File 'lib/flt/num.rb', line 2726 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
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 |
# File 'lib/flt/num.rb', line 2766 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_exponent ⇒ Object
Exponent of the significand as an integer. Synonym of exponent
2705 2706 2707 2708 |
# File 'lib/flt/num.rb', line 2705 def integral_exponent # fractional_exponent - number_of_digits @exp end |
#integral_significand ⇒ Object
Significand as an integer, unsigned. Synonym of coefficient
2700 2701 2702 |
# File 'lib/flt/num.rb', line 2700 def integral_significand @coeff end |
#ln(context = nil) ⇒ Object
Returns the natural (base e) logarithm
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 |
# File 'lib/flt/num.rb', line 2396 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
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 |
# File 'lib/flt/num.rb', line 2458 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
2472 2473 2474 2475 |
# File 'lib/flt/num.rb', line 2472 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
2478 2479 2480 2481 |
# File 'lib/flt/num.rb', line 2478 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).
2297 2298 2299 2300 2301 2302 2303 2304 |
# File 'lib/flt/num.rb', line 2297 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) end |
#minus(context = nil) ⇒ Object
Unary prefix minus operator
1905 1906 1907 |
# File 'lib/flt/num.rb', line 1905 def minus(context=nil) _neg(context) end |
#modulo(other, context = nil) ⇒ Object
Ruby-style modulo: x - y*div(x,y)
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 |
# File 'lib/flt/num.rb', line 2129 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
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 |
# File 'lib/flt/num.rb', line 1736 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).
1517 1518 1519 |
# File 'lib/flt/num.rb', line 1517 def nan? @exp==:nan || @exp==:snan end |
#next_minus(context = nil) ⇒ Object
Largest representable number smaller than itself
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 |
# File 'lib/flt/num.rb', line 1910 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
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 |
# File 'lib/flt/num.rb', line 1941 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.
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 |
# File 'lib/flt/num.rb', line 1974 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
1547 1548 1549 |
# File 'lib/flt/num.rb', line 1547 def nonzero? special? || @coeff>0 end |
#normal?(context = nil) ⇒ Boolean
Returns whether the number is normal
1559 1560 1561 1562 1563 |
# File 'lib/flt/num.rb', line 1559 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.
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 |
# File 'lib/flt/num.rb', line 2271 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_class ⇒ Object
1276 1277 1278 |
# File 'lib/flt/num.rb', line 1276 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'
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 |
# File 'lib/flt/num.rb', line 1568 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_digits ⇒ Object
Number of digits in the significand
2689 2690 2691 2692 |
# File 'lib/flt/num.rb', line 2689 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
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 |
# File 'lib/flt/num.rb', line 2808 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
1900 1901 1902 |
# File 'lib/flt/num.rb', line 1900 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.
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 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 |
# File 'lib/flt/num.rb', line 3092 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)
1522 1523 1524 |
# File 'lib/flt/num.rb', line 1522 def qnan? @exp == :nan end |
#quantize(exp, context = nil, watch_exp = true) ⇒ Object
Quantize so its exponent is the same as that of y.
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 |
# File 'lib/flt/num.rb', line 2851 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 |
#reduce(context = nil) ⇒ Object
Reduces an operand to its simplest form by removing trailing 0s and incrementing the exponent. (formerly called normalize in GDAS)
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 |
# File 'lib/flt/num.rb', line 2240 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 |
#remainder(other, context = nil) ⇒ Object
General Decimal Arithmetic Specification remainder: x - y*divide_int(x,y)
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 |
# File 'lib/flt/num.rb', line 2152 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)
2176 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 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 |
# File 'lib/flt/num.rb', line 2176 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.
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 |
# File 'lib/flt/num.rb', line 2834 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
:index 7 6 5 4 3 2 1 0
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 |
# File 'lib/flt/num.rb', line 2935 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.
2872 2873 2874 2875 2876 2877 2878 |
# File 'lib/flt/num.rb', line 2872 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.
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 |
# File 'lib/flt/num.rb', line 2307 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_exponent ⇒ Object
Synonym for Num#adjusted_exponent()
2679 2680 2681 |
# File 'lib/flt/num.rb', line 2679 def scientific_exponent adjusted_exponent end |
#sign ⇒ Object
Sign of the number: +1 for plus / -1 for minus.
2711 2712 2713 |
# File 'lib/flt/num.rb', line 2711 def sign @sign end |
#snan? ⇒ Boolean
Returns whether the number is a signaling NaN
1527 1528 1529 |
# File 'lib/flt/num.rb', line 1527 def snan? @exp == :snan end |
#special? ⇒ Boolean
Returns whether the number is a special value (NaN or Infinity).
1512 1513 1514 |
# File 'lib/flt/num.rb', line 1512 def special? @exp.instance_of?(Symbol) end |
#split ⇒ Object
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
1507 1508 1509 |
# File 'lib/flt/num.rb', line 1507 def split [@sign, @coeff, @exp] end |
#sqrt(context = nil) ⇒ Object
Square root
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 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 |
# File 'lib/flt/num.rb', line 1828 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
1552 1553 1554 1555 1556 |
# File 'lib/flt/num.rb', line 1552 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
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 |
# File 'lib/flt/num.rb', line 1723 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_f ⇒ Object
Conversion to Float
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 |
# File 'lib/flt/num.rb', line 2522 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_i ⇒ Object
Ruby-style to integer conversion.
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 |
# File 'lib/flt/num.rb', line 2490 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_scale ⇒ Object
Return the value of the number as an signed integer and a scale.
2741 2742 2743 2744 2745 2746 2747 |
# File 'lib/flt/num.rb', line 2741 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.
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 |
# File 'lib/flt/num.rb', line 2881 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.
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 |
# File 'lib/flt/num.rb', line 2897 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_r ⇒ Object
Conversion to Rational. Conversion of special values will raise an exception under Ruby 1.9
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 |
# File 'lib/flt/num.rb', line 2508 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).
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 |
# File 'lib/flt/num.rb', line 3047 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 = args.first || {} context = .delete(:context) if .has_key?(:context) eng = .delete(:eng) if .has_key?(:eng) format(context, .merge(:eng=>eng)) end |
#truncate(opt = {}) ⇒ Object
General truncate operation (as for Float) with same options for precision as Flt::Num#round()
2980 2981 2982 2983 |
# File 'lib/flt/num.rb', line 2980 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)
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 |
# File 'lib/flt/num.rb', line 2541 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
1542 1543 1544 |
# File 'lib/flt/num.rb', line 1542 def zero? @coeff==0 && !special? end |