code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def deepcopy(x, memo=None, _nil=[]): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) y = memo.get(d, _nil) if y is not _nil: return y cls = type(x) copier = _deepcopy_dispatch.get(cls) if copier: y = copier(x, memo) else: try: issc = issubclass(cls, type) except TypeError: # cls is not a class (old Boost; see SF #502085) issc = 0 if issc: y = _deepcopy_atomic(x, memo) else: copier = getattr(x, "__deepcopy__", None) if copier: y = copier(memo) else: reductor = dispatch_table.get(cls) if reductor: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor: rv = reductor(2) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: raise Error( "un(deep)copyable object of type %s" % cls) y = _reconstruct(x, rv, 1, memo) memo[d] = y _keep_alive(x, memo) # Make sure x lives at least as long as d return y
Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info.
deepcopy
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/copy.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/copy.py
MIT
def _keep_alive(x, memo): """Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself... """ try: memo[id(memo)].append(x) except KeyError: # aha, this is the first one :-) memo[id(memo)]=[x]
Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself...
_keep_alive
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/copy.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/copy.py
MIT
def _slotnames(cls): """Return a list of slot names for a given class. This needs to find slots defined by the class and its bases, so we can't simply return the __slots__ attribute. We must walk down the Method Resolution Order and concatenate the __slots__ of each class found there. (This assumes classes don't modify their __slots__ attribute to misrepresent their slots after the class is defined.) """ # Get the value from a cache in the class if possible names = cls.__dict__.get("__slotnames__") if names is not None: return names # Not cached -- calculate the value names = [] if not hasattr(cls, "__slots__"): # This class has no slots pass else: # Slots found -- gather slot names from all base classes for c in cls.__mro__: if "__slots__" in c.__dict__: slots = c.__dict__['__slots__'] # if class has a single slot, it can be given as a string if isinstance(slots, basestring): slots = (slots,) for name in slots: # special descriptors if name in ("__dict__", "__weakref__"): continue # mangled names elif name.startswith('__') and not name.endswith('__'): names.append('_%s%s' % (c.__name__, name)) else: names.append(name) # Cache the outcome in the class if at all possible try: cls.__slotnames__ = names except: pass # But don't die if we can't return names
Return a list of slot names for a given class. This needs to find slots defined by the class and its bases, so we can't simply return the __slots__ attribute. We must walk down the Method Resolution Order and concatenate the __slots__ of each class found there. (This assumes classes don't modify their __slots__ attribute to misrepresent their slots after the class is defined.)
_slotnames
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/copy_reg.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/copy_reg.py
MIT
def remove_extension(module, name, code): """Unregister an extension code. For testing only.""" key = (module, name) if (_extension_registry.get(key) != code or _inverted_registry.get(code) != key): raise ValueError("key %s is not registered with code %s" % (key, code)) del _extension_registry[key] del _inverted_registry[code] if code in _extension_cache: del _extension_cache[code]
Unregister an extension code. For testing only.
remove_extension
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/copy_reg.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/copy_reg.py
MIT
def run(statement, filename=None, sort=-1): """Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this routine attempts to "exec" its first argument and gather profiling statistics from the execution. If no file name is present, then this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line. """ prof = Profile() result = None try: try: prof = prof.run(statement) except SystemExit: pass finally: if filename is not None: prof.dump_stats(filename) else: result = prof.print_stats(sort) return result
Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this routine attempts to "exec" its first argument and gather profiling statistics from the execution. If no file name is present, then this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line.
run
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cProfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cProfile.py
MIT
def runctx(statement, globals, locals, filename=None, sort=-1): """Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run """ prof = Profile() result = None try: try: prof = prof.runctx(statement, globals, locals) except SystemExit: pass finally: if filename is not None: prof.dump_stats(filename) else: result = prof.print_stats(sort) return result
Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run
runctx
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cProfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cProfile.py
MIT
def sniff(self, sample, delimiters=None): """ Returns a dialect (or None) corresponding to the sample """ quotechar, doublequote, delimiter, skipinitialspace = \ self._guess_quote_and_delimiter(sample, delimiters) if not delimiter: delimiter, skipinitialspace = self._guess_delimiter(sample, delimiters) if not delimiter: raise Error, "Could not determine delimiter" class dialect(Dialect): _name = "sniffed" lineterminator = '\r\n' quoting = QUOTE_MINIMAL # escapechar = '' dialect.doublequote = doublequote dialect.delimiter = delimiter # _csv.reader won't accept a quotechar of '' dialect.quotechar = quotechar or '"' dialect.skipinitialspace = skipinitialspace return dialect
Returns a dialect (or None) corresponding to the sample
sniff
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/csv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/csv.py
MIT
def setcontext(context): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() threading.currentThread().__decimal_context__ = context
Set this thread's context to context.
setcontext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def getcontext(): """Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext. """ try: return threading.currentThread().__decimal_context__ except AttributeError: context = Context() threading.currentThread().__decimal_context__ = context return context
Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext.
getcontext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def getcontext(_local=local): """Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext. """ try: return _local.__decimal_context__ except AttributeError: context = Context() _local.__decimal_context__ = context return context
Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext.
getcontext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def setcontext(context, _local=local): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() _local.__decimal_context__ = context
Set this thread's context to context.
setcontext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __new__(cls, value="0", context=None): """Create a decimal point instance. >>> Decimal('3.14') # string input Decimal('3.14') >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal('3.14') >>> Decimal(314) # int or long Decimal('314') >>> Decimal(Decimal(314)) # another decimal instance Decimal('314') >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay Decimal('3.14') """ # Note that the coefficient, self._int, is actually stored as # a string rather than as a tuple of digits. This speeds up # the "digits to integer" and "integer to digits" conversions # that are used in almost every arithmetic operation on # Decimals. This is an internal detail: the as_tuple function # and the Decimal constructor still deal with tuples of # digits. self = object.__new__(cls) # From a string # REs insist on real strings, so we can too. if isinstance(value, basestring): m = _parser(value.strip()) if m is None: if context is None: context = getcontext() return context._raise_error(ConversionSyntax, "Invalid literal for Decimal: %r" % value) if m.group('sign') == "-": self._sign = 1 else: self._sign = 0 intpart = m.group('int') if intpart is not None: # finite number fracpart = m.group('frac') or '' exp = int(m.group('exp') or '0') self._int = str(int(intpart+fracpart)) self._exp = exp - len(fracpart) self._is_special = False else: diag = m.group('diag') if diag is not None: # NaN self._int = str(int(diag or '0')).lstrip('0') if m.group('signal'): self._exp = 'N' else: self._exp = 'n' else: # infinity self._int = '0' self._exp = 'F' self._is_special = True return self # From an integer if isinstance(value, (int,long)): if value >= 0: self._sign = 0 else: self._sign = 1 self._exp = 0 self._int = str(abs(value)) self._is_special = False return self # From another decimal if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self # From an internal working value if isinstance(value, _WorkRep): self._sign = value.sign self._int = str(value.int) self._exp = int(value.exp) self._is_special = False return self # tuple/list conversion (possibly from as_tuple()) if isinstance(value, (list,tuple)): if len(value) != 3: raise ValueError('Invalid tuple size in creation of Decimal ' 'from list or tuple. The list or tuple ' 'should have exactly three elements.') # process sign. The isinstance test rejects floats if not (isinstance(value[0], (int, long)) and value[0] in (0,1)): raise ValueError("Invalid sign. The first value in the tuple " "should be an integer; either 0 for a " "positive number or 1 for a negative number.") self._sign = value[0] if value[2] == 'F': # infinity: value[1] is ignored self._int = '0' self._exp = value[2] self._is_special = True else: # process and validate the digits in value[1] digits = [] for digit in value[1]: if isinstance(digit, (int, long)) and 0 <= digit <= 9: # skip leading zeros if digits or digit != 0: digits.append(digit) else: raise ValueError("The second value in the tuple must " "be composed of integers in the range " "0 through 9.") if value[2] in ('n', 'N'): # NaN: digits form the diagnostic self._int = ''.join(map(str, digits)) self._exp = value[2] self._is_special = True elif isinstance(value[2], (int, long)): # finite number: digits give the coefficient self._int = ''.join(map(str, digits or [0])) self._exp = value[2] self._is_special = False else: raise ValueError("The third value in the tuple must " "be an integer, or one of the " "strings 'F', 'n', 'N'.") return self if isinstance(value, float): value = Decimal.from_float(value) self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self raise TypeError("Cannot convert %r to Decimal" % value)
Create a decimal point instance. >>> Decimal('3.14') # string input Decimal('3.14') >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal('3.14') >>> Decimal(314) # int or long Decimal('314') >>> Decimal(Decimal(314)) # another decimal instance Decimal('314') >>> Decimal(' 3.14 \n') # leading and trailing whitespace okay Decimal('3.14')
__new__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def from_float(cls, f): """Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0.1000000000000000055511151231257827021181583404541015625. >>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(-float('inf')) Decimal('-Infinity') >>> Decimal.from_float(-0.0) Decimal('-0') """ if isinstance(f, (int, long)): # handle integer inputs return cls(f) if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float return cls(repr(f)) if _math.copysign(1.0, f) == 1.0: sign = 0 else: sign = 1 n, d = abs(f).as_integer_ratio() k = d.bit_length() - 1 result = _dec_from_triple(sign, str(n*5**k), -k) if cls is Decimal: return result else: return cls(result)
Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0.1000000000000000055511151231257827021181583404541015625. >>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(-float('inf')) Decimal('-Infinity') >>> Decimal.from_float(-0.0) Decimal('-0')
from_float
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _isnan(self): """Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN """ if self._is_special: exp = self._exp if exp == 'n': return 1 elif exp == 'N': return 2 return 0
Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN
_isnan
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _isinfinity(self): """Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF """ if self._exp == 'F': if self._sign: return -1 return 1 return 0
Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF
_isinfinity
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _check_nans(self, other=None, context=None): """Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations. """ self_is_nan = self._isnan() if other is None: other_is_nan = False else: other_is_nan = other._isnan() if self_is_nan or other_is_nan: if context is None: context = getcontext() if self_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', self) if other_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', other) if self_is_nan: return self._fix_nan(context) return other._fix_nan(context) return 0
Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations.
_check_nans
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _compare_check_nans(self, other, context): """Version of _check_nans used for the signaling comparisons compare_signal, __le__, __lt__, __ge__, __gt__. Signal InvalidOperation if either self or other is a (quiet or signaling) NaN. Signaling NaNs take precedence over quiet NaNs. Return 0 if neither operand is a NaN. """ if context is None: context = getcontext() if self._is_special or other._is_special: if self.is_snan(): return context._raise_error(InvalidOperation, 'comparison involving sNaN', self) elif other.is_snan(): return context._raise_error(InvalidOperation, 'comparison involving sNaN', other) elif self.is_qnan(): return context._raise_error(InvalidOperation, 'comparison involving NaN', self) elif other.is_qnan(): return context._raise_error(InvalidOperation, 'comparison involving NaN', other) return 0
Version of _check_nans used for the signaling comparisons compare_signal, __le__, __lt__, __ge__, __gt__. Signal InvalidOperation if either self or other is a (quiet or signaling) NaN. Signaling NaNs take precedence over quiet NaNs. Return 0 if neither operand is a NaN.
_compare_check_nans
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _cmp(self, other): """Compare the two non-NaN decimal instances self and other. Returns -1 if self < other, 0 if self == other and 1 if self > other. This routine is for internal use only.""" if self._is_special or other._is_special: self_inf = self._isinfinity() other_inf = other._isinfinity() if self_inf == other_inf: return 0 elif self_inf < other_inf: return -1 else: return 1 # check for zeros; Decimal('0') == Decimal('-0') if not self: if not other: return 0 else: return -((-1)**other._sign) if not other: return (-1)**self._sign # If different signs, neg one is less if other._sign < self._sign: return -1 if self._sign < other._sign: return 1 self_adjusted = self.adjusted() other_adjusted = other.adjusted() if self_adjusted == other_adjusted: self_padded = self._int + '0'*(self._exp - other._exp) other_padded = other._int + '0'*(other._exp - self._exp) if self_padded == other_padded: return 0 elif self_padded < other_padded: return -(-1)**self._sign else: return (-1)**self._sign elif self_adjusted > other_adjusted: return (-1)**self._sign else: # self_adjusted < other_adjusted return -((-1)**self._sign)
Compare the two non-NaN decimal instances self and other. Returns -1 if self < other, 0 if self == other and 1 if self > other. This routine is for internal use only.
_cmp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def compare(self, other, context=None): """Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances. """ other = _convert_other(other, raiseit=True) # Compare(NaN, NaN) = NaN if (self._is_special or other and other._is_special): ans = self._check_nans(other, context) if ans: return ans return Decimal(self._cmp(other))
Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances.
compare
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __repr__(self): """Represents the number as an instance of Decimal.""" # Invariant: eval(repr(d)) == d return "Decimal('%s')" % str(self)
Represents the number as an instance of Decimal.
__repr__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __str__(self, eng=False, context=None): """Return string representation of the number in scientific notation. Captures all of the information in the underlying representation. """ sign = ['', '-'][self._sign] if self._is_special: if self._exp == 'F': return sign + 'Infinity' elif self._exp == 'n': return sign + 'NaN' + self._int else: # self._exp == 'N' return sign + 'sNaN' + self._int # number of digits of self._int to left of decimal point leftdigits = self._exp + len(self._int) # dotplace is number of digits of self._int to the left of the # decimal point in the mantissa of the output string (that is, # after adjusting the exponent) if self._exp <= 0 and leftdigits > -6: # no exponent required dotplace = leftdigits elif not eng: # usual scientific notation: 1 digit on left of the point dotplace = 1 elif self._int == '0': # engineering notation, zero dotplace = (leftdigits + 1) % 3 - 1 else: # engineering notation, nonzero dotplace = (leftdigits - 1) % 3 + 1 if dotplace <= 0: intpart = '0' fracpart = '.' + '0'*(-dotplace) + self._int elif dotplace >= len(self._int): intpart = self._int+'0'*(dotplace-len(self._int)) fracpart = '' else: intpart = self._int[:dotplace] fracpart = '.' + self._int[dotplace:] if leftdigits == dotplace: exp = '' else: if context is None: context = getcontext() exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) return sign + intpart + fracpart + exp
Return string representation of the number in scientific notation. Captures all of the information in the underlying representation.
__str__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __neg__(self, context=None): """Returns a copy with the sign switched. Rounds, if it has reason. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if context is None: context = getcontext() if not self and context.rounding != ROUND_FLOOR: # -Decimal('0') is Decimal('0'), not Decimal('-0'), except # in ROUND_FLOOR rounding mode. ans = self.copy_abs() else: ans = self.copy_negate() return ans._fix(context)
Returns a copy with the sign switched. Rounds, if it has reason.
__neg__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __pos__(self, context=None): """Returns a copy, unless it is a sNaN. Rounds the number (if more than precision digits) """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if context is None: context = getcontext() if not self and context.rounding != ROUND_FLOOR: # + (-0) = 0, except in ROUND_FLOOR rounding mode. ans = self.copy_abs() else: ans = Decimal(self) return ans._fix(context)
Returns a copy, unless it is a sNaN. Rounds the number (if more than precision digits)
__pos__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __abs__(self, round=True, context=None): """Returns the absolute value of self. If the keyword argument 'round' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs(). """ if not round: return self.copy_abs() if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans
Returns the absolute value of self. If the keyword argument 'round' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs().
__abs__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __add__(self, other, context=None): """Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): # If both INF, same sign => same as both, opposite => error. if self._sign != other._sign and other._isinfinity(): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other) # Can't both be infinity here exp = min(self._exp, other._exp) negativezero = 0 if context.rounding == ROUND_FLOOR and self._sign != other._sign: # If the answer is 0, the sign should be negative, in this case. negativezero = 1 if not self and not other: sign = min(self._sign, other._sign) if negativezero: sign = 1 ans = _dec_from_triple(sign, '0', exp) ans = ans._fix(context) return ans if not self: exp = max(exp, other._exp - context.prec-1) ans = other._rescale(exp, context.rounding) ans = ans._fix(context) return ans if not other: exp = max(exp, self._exp - context.prec-1) ans = self._rescale(exp, context.rounding) ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) op1, op2 = _normalize(op1, op2, context.prec) result = _WorkRep() if op1.sign != op2.sign: # Equal and opposite if op1.int == op2.int: ans = _dec_from_triple(negativezero, '0', exp) ans = ans._fix(context) return ans if op1.int < op2.int: op1, op2 = op2, op1 # OK, now abs(op1) > abs(op2) if op1.sign == 1: result.sign = 1 op1.sign, op2.sign = op2.sign, op1.sign else: result.sign = 0 # So we know the sign, and op1 > 0. elif op1.sign == 1: result.sign = 1 op1.sign, op2.sign = (0, 0) else: result.sign = 0 # Now, op1 > abs(op2) > 0 if op2.sign == 0: result.int = op1.int + op2.int else: result.int = op1.int - op2.int result.exp = op1.exp ans = Decimal(result) ans = ans._fix(context) return ans
Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors.
__add__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __mul__(self, other, context=None): """Return self * other. (+-) INF * 0 (or its reverse) raise InvalidOperation. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() resultsign = self._sign ^ other._sign if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if not other: return context._raise_error(InvalidOperation, '(+-)INF * 0') return _SignedInfinity[resultsign] if other._isinfinity(): if not self: return context._raise_error(InvalidOperation, '0 * (+-)INF') return _SignedInfinity[resultsign] resultexp = self._exp + other._exp # Special case for multiplying by zero if not self or not other: ans = _dec_from_triple(resultsign, '0', resultexp) # Fixing in case the exponent is out of bounds ans = ans._fix(context) return ans # Special case for multiplying by power of 10 if self._int == '1': ans = _dec_from_triple(resultsign, other._int, resultexp) ans = ans._fix(context) return ans if other._int == '1': ans = _dec_from_triple(resultsign, self._int, resultexp) ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) ans = ans._fix(context) return ans
Return self * other. (+-) INF * 0 (or its reverse) raise InvalidOperation.
__mul__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _divide(self, other, context): """Return (self // other, self % other), to context.prec precision. Assumes that neither self nor other is a NaN, that self is not infinite and that other is nonzero. """ sign = self._sign ^ other._sign if other._isinfinity(): ideal_exp = self._exp else: ideal_exp = min(self._exp, other._exp) expdiff = self.adjusted() - other.adjusted() if not self or other._isinfinity() or expdiff <= -2: return (_dec_from_triple(sign, '0', 0), self._rescale(ideal_exp, context.rounding)) if expdiff <= context.prec: op1 = _WorkRep(self) op2 = _WorkRep(other) if op1.exp >= op2.exp: op1.int *= 10**(op1.exp - op2.exp) else: op2.int *= 10**(op2.exp - op1.exp) q, r = divmod(op1.int, op2.int) if q < 10**context.prec: return (_dec_from_triple(sign, str(q), 0), _dec_from_triple(self._sign, str(r), ideal_exp)) # Here the quotient is too large to be representable ans = context._raise_error(DivisionImpossible, 'quotient too large in //, % or divmod') return ans, ans
Return (self // other, self % other), to context.prec precision. Assumes that neither self nor other is a NaN, that self is not infinite and that other is nonzero.
_divide
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def remainder_near(self, other, context=None): """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans # self == +/-infinity -> InvalidOperation if self._isinfinity(): return context._raise_error(InvalidOperation, 'remainder_near(infinity, x)') # other == 0 -> either InvalidOperation or DivisionUndefined if not other: if self: return context._raise_error(InvalidOperation, 'remainder_near(x, 0)') else: return context._raise_error(DivisionUndefined, 'remainder_near(0, 0)') # other = +/-infinity -> remainder = self if other._isinfinity(): ans = Decimal(self) return ans._fix(context) # self = 0 -> remainder = self, with ideal exponent ideal_exponent = min(self._exp, other._exp) if not self: ans = _dec_from_triple(self._sign, '0', ideal_exponent) return ans._fix(context) # catch most cases of large or small quotient expdiff = self.adjusted() - other.adjusted() if expdiff >= context.prec + 1: # expdiff >= prec+1 => abs(self/other) > 10**prec return context._raise_error(DivisionImpossible) if expdiff <= -2: # expdiff <= -2 => abs(self/other) < 0.1 ans = self._rescale(ideal_exponent, context.rounding) return ans._fix(context) # adjust both arguments to have the same exponent, then divide op1 = _WorkRep(self) op2 = _WorkRep(other) if op1.exp >= op2.exp: op1.int *= 10**(op1.exp - op2.exp) else: op2.int *= 10**(op2.exp - op1.exp) q, r = divmod(op1.int, op2.int) # remainder is r*10**ideal_exponent; other is +/-op2.int * # 10**ideal_exponent. Apply correction to ensure that # abs(remainder) <= abs(other)/2 if 2*r + (q&1) > op2.int: r -= op2.int q += 1 if q >= 10**context.prec: return context._raise_error(DivisionImpossible) # result has same sign as self unless r is negative sign = self._sign if r < 0: sign = 1-sign r = -r ans = _dec_from_triple(sign, str(r), ideal_exponent) return ans._fix(context)
Remainder nearest to 0- abs(remainder-near) <= other/2
remainder_near
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __int__(self): """Converts self to an int, truncating if necessary.""" if self._is_special: if self._isnan(): raise ValueError("Cannot convert NaN to integer") elif self._isinfinity(): raise OverflowError("Cannot convert infinity to integer") s = (-1)**self._sign if self._exp >= 0: return s*int(self._int)*10**self._exp else: return s*int(self._int[:self._exp] or '0')
Converts self to an int, truncating if necessary.
__int__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _fix_nan(self, context): """Decapitate the payload of a NaN to fit the context""" payload = self._int # maximum length of payload is precision if _clamp=0, # precision-1 if _clamp=1. max_payload_len = context.prec - context._clamp if len(payload) > max_payload_len: payload = payload[len(payload)-max_payload_len:].lstrip('0') return _dec_from_triple(self._sign, payload, self._exp, True) return Decimal(self)
Decapitate the payload of a NaN to fit the context
_fix_nan
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _fix(self, context): """Round if it is necessary to keep self within prec precision. Rounds and fixes the exponent. Does not raise on a sNaN. Arguments: self - Decimal instance context - context used. """ if self._is_special: if self._isnan(): # decapitate payload if necessary return self._fix_nan(context) else: # self is +/-Infinity; return unaltered return Decimal(self) # if self is zero then exponent should be between Etiny and # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. Etiny = context.Etiny() Etop = context.Etop() if not self: exp_max = [context.Emax, Etop][context._clamp] new_exp = min(max(self._exp, Etiny), exp_max) if new_exp != self._exp: context._raise_error(Clamped) return _dec_from_triple(self._sign, '0', new_exp) else: return Decimal(self) # exp_min is the smallest allowable exponent of the result, # equal to max(self.adjusted()-context.prec+1, Etiny) exp_min = len(self._int) + self._exp - context.prec if exp_min > Etop: # overflow: exp_min > Etop iff self.adjusted() > Emax ans = context._raise_error(Overflow, 'above Emax', self._sign) context._raise_error(Inexact) context._raise_error(Rounded) return ans self_is_subnormal = exp_min < Etiny if self_is_subnormal: exp_min = Etiny # round if self has too many digits if self._exp < exp_min: digits = len(self._int) + self._exp - exp_min if digits < 0: self = _dec_from_triple(self._sign, '1', exp_min-1) digits = 0 rounding_method = self._pick_rounding_function[context.rounding] changed = rounding_method(self, digits) coeff = self._int[:digits] or '0' if changed > 0: coeff = str(int(coeff)+1) if len(coeff) > context.prec: coeff = coeff[:-1] exp_min += 1 # check whether the rounding pushed the exponent out of range if exp_min > Etop: ans = context._raise_error(Overflow, 'above Emax', self._sign) else: ans = _dec_from_triple(self._sign, coeff, exp_min) # raise the appropriate signals, taking care to respect # the precedence described in the specification if changed and self_is_subnormal: context._raise_error(Underflow) if self_is_subnormal: context._raise_error(Subnormal) if changed: context._raise_error(Inexact) context._raise_error(Rounded) if not ans: # raise Clamped on underflow to 0 context._raise_error(Clamped) return ans if self_is_subnormal: context._raise_error(Subnormal) # fold down if _clamp == 1 and self has too few digits if context._clamp == 1 and self._exp > Etop: context._raise_error(Clamped) self_padded = self._int + '0'*(self._exp - Etop) return _dec_from_triple(self._sign, self_padded, Etop) # here self was representable to begin with; return unchanged return Decimal(self)
Round if it is necessary to keep self within prec precision. Rounds and fixes the exponent. Does not raise on a sNaN. Arguments: self - Decimal instance context - context used.
_fix
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _round_down(self, prec): """Also known as round-towards-0, truncate.""" if _all_zeros(self._int, prec): return 0 else: return -1
Also known as round-towards-0, truncate.
_round_down
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _round_half_even(self, prec): """Round 5 to even, rest to nearest.""" if _exact_half(self._int, prec) and \ (prec == 0 or self._int[prec-1] in '02468'): return -1 else: return self._round_half_up(prec)
Round 5 to even, rest to nearest.
_round_half_even
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _round_ceiling(self, prec): """Rounds up (not away from 0 if negative.)""" if self._sign: return self._round_down(prec) else: return -self._round_down(prec)
Rounds up (not away from 0 if negative.)
_round_ceiling
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _round_floor(self, prec): """Rounds down (not towards 0 if negative)""" if not self._sign: return self._round_down(prec) else: return -self._round_down(prec)
Rounds down (not towards 0 if negative)
_round_floor
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _round_05up(self, prec): """Round down unless digit prec-1 is 0 or 5.""" if prec and self._int[prec-1] not in '05': return self._round_down(prec) else: return -self._round_down(prec)
Round down unless digit prec-1 is 0 or 5.
_round_05up
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def fma(self, other, third, context=None): """Fused multiply-add. Returns self*other+third with no rounding of the intermediate product self*other. self and other are multiplied together, with no rounding of the result. The third operand is then added to the result, and a single final rounding is performed. """ other = _convert_other(other, raiseit=True) # compute product; raise InvalidOperation if either operand is # a signaling NaN or if the product is zero times infinity. if self._is_special or other._is_special: if context is None: context = getcontext() if self._exp == 'N': return context._raise_error(InvalidOperation, 'sNaN', self) if other._exp == 'N': return context._raise_error(InvalidOperation, 'sNaN', other) if self._exp == 'n': product = self elif other._exp == 'n': product = other elif self._exp == 'F': if not other: return context._raise_error(InvalidOperation, 'INF * 0 in fma') product = _SignedInfinity[self._sign ^ other._sign] elif other._exp == 'F': if not self: return context._raise_error(InvalidOperation, '0 * INF in fma') product = _SignedInfinity[self._sign ^ other._sign] else: product = _dec_from_triple(self._sign ^ other._sign, str(int(self._int) * int(other._int)), self._exp + other._exp) third = _convert_other(third, raiseit=True) return product.__add__(third, context)
Fused multiply-add. Returns self*other+third with no rounding of the intermediate product self*other. self and other are multiplied together, with no rounding of the result. The third operand is then added to the result, and a single final rounding is performed.
fma
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _power_exact(self, other, p): """Attempt to compute self**other exactly. Given Decimals self and other and an integer p, attempt to compute an exact result for the power self**other, with p digits of precision. Return None if self**other is not exactly representable in p digits. Assumes that elimination of special cases has already been performed: self and other must both be nonspecial; self must be positive and not numerically equal to 1; other must be nonzero. For efficiency, other._exp should not be too large, so that 10**abs(other._exp) is a feasible calculation.""" # In the comments below, we write x for the value of self and y for the # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc # and yc positive integers not divisible by 10. # The main purpose of this method is to identify the *failure* # of x**y to be exactly representable with as little effort as # possible. So we look for cheap and easy tests that # eliminate the possibility of x**y being exact. Only if all # these tests are passed do we go on to actually compute x**y. # Here's the main idea. Express y as a rational number m/n, with m and # n relatively prime and n>0. Then for x**y to be exactly # representable (at *any* precision), xc must be the nth power of a # positive integer and xe must be divisible by n. If y is negative # then additionally xc must be a power of either 2 or 5, hence a power # of 2**n or 5**n. # # There's a limit to how small |y| can be: if y=m/n as above # then: # # (1) if xc != 1 then for the result to be representable we # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= # 2**(1/|y|), hence xc**|y| < 2 and the result is not # representable. # # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if # |y| < 1/|xe| then the result is not representable. # # Note that since x is not equal to 1, at least one of (1) and # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. # # There's also a limit to how large y can be, at least if it's # positive: the normalized result will have coefficient xc**y, # so if it's representable then xc**y < 10**p, and y < # p/log10(xc). Hence if y*log10(xc) >= p then the result is # not exactly representable. # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, # so |y| < 1/xe and the result is not representable. # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| # < 1/nbits(xc). x = _WorkRep(self) xc, xe = x.int, x.exp while xc % 10 == 0: xc //= 10 xe += 1 y = _WorkRep(other) yc, ye = y.int, y.exp while yc % 10 == 0: yc //= 10 ye += 1 # case where xc == 1: result is 10**(xe*y), with xe*y # required to be an integer if xc == 1: xe *= yc # result is now 10**(xe * 10**ye); xe * 10**ye must be integral while xe % 10 == 0: xe //= 10 ye += 1 if ye < 0: return None exponent = xe * 10**ye if y.sign == 1: exponent = -exponent # if other is a nonnegative integer, use ideal exponent if other._isinteger() and other._sign == 0: ideal_exponent = self._exp*int(other) zeros = min(exponent-ideal_exponent, p-1) else: zeros = 0 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) # case where y is negative: xc must be either a power # of 2 or a power of 5. if y.sign == 1: last_digit = xc % 10 if last_digit in (2,4,6,8): # quick test for power of 2 if xc & -xc != xc: return None # now xc is a power of 2; e is its exponent e = _nbits(xc)-1 # We now have: # # x = 2**e * 10**xe, e > 0, and y < 0. # # The exact result is: # # x**y = 5**(-e*y) * 10**(e*y + xe*y) # # provided that both e*y and xe*y are integers. Note that if # 5**(-e*y) >= 10**p, then the result can't be expressed # exactly with p digits of precision. # # Using the above, we can guard against large values of ye. # 93/65 is an upper bound for log(10)/log(5), so if # # ye >= len(str(93*p//65)) # # then # # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5), # # so 5**(-e*y) >= 10**p, and the coefficient of the result # can't be expressed in p digits. # emax >= largest e such that 5**e < 10**p. emax = p*93//65 if ye >= len(str(emax)): return None # Find -e*y and -xe*y; both must be integers e = _decimal_lshift_exact(e * yc, ye) xe = _decimal_lshift_exact(xe * yc, ye) if e is None or xe is None: return None if e > emax: return None xc = 5**e elif last_digit == 5: # e >= log_5(xc) if xc is a power of 5; we have # equality all the way up to xc=5**2658 e = _nbits(xc)*28//65 xc, remainder = divmod(5**e, xc) if remainder: return None while xc % 5 == 0: xc //= 5 e -= 1 # Guard against large values of ye, using the same logic as in # the 'xc is a power of 2' branch. 10/3 is an upper bound for # log(10)/log(2). emax = p*10//3 if ye >= len(str(emax)): return None e = _decimal_lshift_exact(e * yc, ye) xe = _decimal_lshift_exact(xe * yc, ye) if e is None or xe is None: return None if e > emax: return None xc = 2**e else: return None if xc >= 10**p: return None xe = -e-xe return _dec_from_triple(0, str(xc), xe) # now y is positive; find m and n such that y = m/n if ye >= 0: m, n = yc*10**ye, 1 else: if xe != 0 and len(str(abs(yc*xe))) <= -ye: return None xc_bits = _nbits(xc) if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: return None m, n = yc, 10**(-ye) while m % 2 == n % 2 == 0: m //= 2 n //= 2 while m % 5 == n % 5 == 0: m //= 5 n //= 5 # compute nth root of xc*10**xe if n > 1: # if 1 < xc < 2**n then xc isn't an nth power if xc != 1 and xc_bits <= n: return None xe, rem = divmod(xe, n) if rem != 0: return None # compute nth root of xc using Newton's method a = 1L << -(-_nbits(xc)//n) # initial estimate while True: q, r = divmod(xc, a**(n-1)) if a <= q: break else: a = (a*(n-1) + q)//n if not (a == q and r == 0): return None xc = a # now xc*10**xe is the nth root of the original xc*10**xe # compute mth power of xc*10**xe # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > # 10**p and the result is not representable. if xc > 1 and m > p*100//_log10_lb(xc): return None xc = xc**m xe *= m if xc > 10**p: return None # by this point the result *is* exactly representable # adjust the exponent to get as close as possible to the ideal # exponent, if necessary str_xc = str(xc) if other._isinteger() and other._sign == 0: ideal_exponent = self._exp*int(other) zeros = min(xe-ideal_exponent, p-len(str_xc)) else: zeros = 0 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Attempt to compute self**other exactly. Given Decimals self and other and an integer p, attempt to compute an exact result for the power self**other, with p digits of precision. Return None if self**other is not exactly representable in p digits. Assumes that elimination of special cases has already been performed: self and other must both be nonspecial; self must be positive and not numerically equal to 1; other must be nonzero. For efficiency, other._exp should not be too large, so that 10**abs(other._exp) is a feasible calculation.
_power_exact
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def __pow__(self, other, modulo=None, context=None): """Return self ** other [ % modulo]. With two arguments, compute self**other. 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 - either self or other (or both) must be nonzero - modulo must be nonzero and must have at most p digits, where p is the context precision. If any of these restrictions is violated the InvalidOperation flag is raised. The result of pow(self, other, modulo) is identical to the result that would be obtained by computing (self**other) % modulo with unbounded precision, but is computed more efficiently. It is always exact. """ if modulo is not None: return self._power_modulo(other, modulo, context) other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() # either argument is a NaN => result is NaN ans = self._check_nans(other, context) if ans: return ans # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) if not other: if not self: return context._raise_error(InvalidOperation, '0 ** 0') else: return _One # result has sign 1 iff self._sign is 1 and other is an odd integer result_sign = 0 if self._sign == 1: if other._isinteger(): if not other._iseven(): result_sign = 1 else: # -ve**noninteger = NaN # (-0)**noninteger = 0**noninteger if self: return context._raise_error(InvalidOperation, 'x ** y with x negative and y not an integer') # negate self, without doing any unwanted rounding self = self.copy_negate() # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity if not self: if other._sign == 0: return _dec_from_triple(result_sign, '0', 0) else: return _SignedInfinity[result_sign] # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 if self._isinfinity(): if other._sign == 0: return _SignedInfinity[result_sign] else: return _dec_from_triple(result_sign, '0', 0) # 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 == _One: if other._isinteger(): # 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 elif other > context.prec: multiplier = context.prec else: multiplier = int(other) exp = self._exp * multiplier if exp < 1-context.prec: exp = 1-context.prec context._raise_error(Rounded) else: context._raise_error(Inexact) context._raise_error(Rounded) exp = 1-context.prec return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) # compute adjusted exponent of self self_adj = self.adjusted() # self ** infinity is infinity if self > 1, 0 if self < 1 # self ** -infinity is infinity if self < 1, 0 if self > 1 if other._isinfinity(): if (other._sign == 0) == (self_adj < 0): return _dec_from_triple(result_sign, '0', 0) else: return _SignedInfinity[result_sign] # from here on, the result always goes through the call # to _fix at the end of this function. ans = None exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence # self**other >= 10**(Emax+1), so overflow occurs. The test # for underflow is similar. bound = self._log10_exp_bound() + other.adjusted() if (self_adj >= 0) == (other._sign == 0): # self > 1 and other +ve, or self < 1 and other -ve # possibility of overflow if bound >= len(str(context.Emax)): ans = _dec_from_triple(result_sign, '1', context.Emax+1) else: # self > 1 and other -ve, or self < 1 and other +ve # possibility of underflow to 0 Etiny = context.Etiny() if bound >= len(str(-Etiny)): ans = _dec_from_triple(result_sign, '1', Etiny-1) # try for an exact result with precision +1 if ans is None: ans = self._power_exact(other, context.prec + 1) if ans is not None: if result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: p = context.prec x = _WorkRep(self) xc, xe = x.int, x.exp y = _WorkRep(other) yc, ye = y.int, y.exp if y.sign == 1: yc = -yc # compute correctly rounded result: start with precision +3, # then increase precision until result is unambiguously roundable extra = 3 while True: coeff, exp = _dpower(xc, xe, yc, ye, p+extra) if coeff % (5*10**(len(str(coeff))-p-1)): break extra += 3 ans = _dec_from_triple(result_sign, str(coeff), exp) # unlike exp, ln and log10, the power function respects the # rounding mode; no need to switch to ROUND_HALF_EVEN here # There's a difficulty here when 'other' is not an integer and # the result is exact. In this case, the specification # requires that the Inexact flag be raised (in spite of # exactness), but since the result is exact _fix won't do this # for us. (Correspondingly, the Underflow signal should also # be raised for subnormal results.) We can't directly raise # these signals either before or after calling _fix, since # that would violate the precedence for signals. So we wrap # the ._fix call in a temporary context, and reraise # afterwards. if exact and not other._isinteger(): # pad with zeros up to length context.prec+1 if necessary; this # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) # create a copy of the current context, with cleared flags/traps newcontext = context.copy() newcontext.clear_flags() for exception in _signals: newcontext.traps[exception] = 0 # round in the new context ans = ans._fix(newcontext) # raise Inexact, and if necessary, Underflow newcontext._raise_error(Inexact) if newcontext.flags[Subnormal]: newcontext._raise_error(Underflow) # propagate signals to the original context; _fix could # have raised any of Overflow, Underflow, Subnormal, # Inexact, Rounded, Clamped. Overflow needs the correct # arguments. Note that the order of the exceptions is # important here. if newcontext.flags[Overflow]: context._raise_error(Overflow, 'above Emax', ans._sign) for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: if newcontext.flags[exception]: context._raise_error(exception) else: ans = ans._fix(context) return ans
Return self ** other [ % modulo]. With two arguments, compute self**other. 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 - either self or other (or both) must be nonzero - modulo must be nonzero and must have at most p digits, where p is the context precision. If any of these restrictions is violated the InvalidOperation flag is raised. The result of pow(self, other, modulo) is identical to the result that would be obtained by computing (self**other) % modulo with unbounded precision, but is computed more efficiently. It is always exact.
__pow__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" if context is None: context = getcontext() if self._is_special: ans = self._check_nans(context=context) if ans: return ans dup = self._fix(context) if dup._isinfinity(): return dup if not dup: return _dec_from_triple(dup._sign, '0', 0) exp_max = [context.Emax, context.Etop()][context._clamp] end = len(dup._int) exp = dup._exp while dup._int[end-1] == '0' and exp < exp_max: exp += 1 end -= 1 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Normalize- strip trailing 0s, change anything equal to 0 to 0e0
normalize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def quantize(self, exp, rounding=None, context=None, watchexp=True): """Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking. """ exp = _convert_other(exp, raiseit=True) if context is None: context = getcontext() if rounding is None: rounding = context.rounding if self._is_special or exp._is_special: ans = self._check_nans(exp, context) if ans: return ans if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): return Decimal(self) # if both are inf, it is OK return context._raise_error(InvalidOperation, 'quantize with one INF') # if we're not watching exponents, do a simple rescale if not watchexp: ans = self._rescale(exp._exp, rounding) # raise Inexact and Rounded where appropriate if ans._exp > self._exp: context._raise_error(Rounded) if ans != self: context._raise_error(Inexact) return ans # exp._exp should be between Etiny and Emax if not (context.Etiny() <= exp._exp <= context.Emax): return context._raise_error(InvalidOperation, 'target exponent out of bounds in quantize') if not self: ans = _dec_from_triple(self._sign, '0', exp._exp) return ans._fix(context) self_adjusted = self.adjusted() if self_adjusted > context.Emax: return context._raise_error(InvalidOperation, 'exponent of quantize result too large for current context') if self_adjusted - exp._exp + 1 > context.prec: return context._raise_error(InvalidOperation, 'quantize result has too many digits for current context') ans = self._rescale(exp._exp, rounding) if ans.adjusted() > context.Emax: return context._raise_error(InvalidOperation, 'exponent of quantize result too large for current context') if len(ans._int) > context.prec: return context._raise_error(InvalidOperation, 'quantize result has too many digits for current context') # raise appropriate flags if ans and ans.adjusted() < context.Emin: context._raise_error(Subnormal) if ans._exp > self._exp: if ans != self: context._raise_error(Inexact) context._raise_error(Rounded) # call to fix takes care of any necessary folddown, and # signals Clamped if necessary ans = ans._fix(context) return ans
Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking.
quantize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def same_quantum(self, other): """Return True if self and other have the same exponent; otherwise return False. 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. """ other = _convert_other(other, raiseit=True) if self._is_special or other._is_special: return (self.is_nan() and other.is_nan() or self.is_infinite() and other.is_infinite()) return self._exp == other._exp
Return True if self and other have the same exponent; otherwise return False. 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.
same_quantum
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _rescale(self, exp, rounding): """Rescale self 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 """ if self._is_special: return Decimal(self) if not self: return _dec_from_triple(self._sign, '0', exp) if self._exp >= exp: # pad answer with zeros if necessary return _dec_from_triple(self._sign, self._int + '0'*(self._exp - exp), exp) # too many digits; round and lose data. If self.adjusted() < # exp-1, replace self by 10**(exp-1) before rounding digits = len(self._int) + self._exp - exp if digits < 0: self = _dec_from_triple(self._sign, '1', exp-1) digits = 0 this_function = self._pick_rounding_function[rounding] changed = this_function(self, digits) coeff = self._int[:digits] or '0' if changed == 1: coeff = str(int(coeff)+1) return _dec_from_triple(self._sign, coeff, exp)
Rescale self 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
_rescale
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _round(self, places, rounding): """Round a nonzero, nonspecial Decimal to a fixed number of significant figures, using the given rounding mode. Infinities, NaNs and zeros are returned unaltered. This operation is quiet: it raises no flags, and uses no information from the context. """ if places <= 0: raise ValueError("argument should be at least 1 in _round") if self._is_special or not self: return Decimal(self) ans = self._rescale(self.adjusted()+1-places, rounding) # it can happen that the rescale alters the adjusted exponent; # for example when rounding 99.97 to 3 significant figures. # When this happens we end up with an extra 0 at the end of # the number; a second rescale fixes this. if ans.adjusted() != self.adjusted(): ans = ans._rescale(ans.adjusted()+1-places, rounding) return ans
Round a nonzero, nonspecial Decimal to a fixed number of significant figures, using the given rounding mode. Infinities, NaNs and zeros are returned unaltered. This operation is quiet: it raises no flags, and uses no information from the context.
_round
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def to_integral_exact(self, rounding=None, context=None): """Rounds to a nearby integer. If no rounding mode is specified, take the rounding mode from the context. This method raises the Rounded and Inexact flags when appropriate. See also: to_integral_value, which does exactly the same as this method except that it doesn't raise Inexact or Rounded. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self) if self._exp >= 0: return Decimal(self) if not self: return _dec_from_triple(self._sign, '0', 0) if context is None: context = getcontext() if rounding is None: rounding = context.rounding ans = self._rescale(0, rounding) if ans != self: context._raise_error(Inexact) context._raise_error(Rounded) return ans
Rounds to a nearby integer. If no rounding mode is specified, take the rounding mode from the context. This method raises the Rounded and Inexact flags when appropriate. See also: to_integral_value, which does exactly the same as this method except that it doesn't raise Inexact or Rounded.
to_integral_exact
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def to_integral_value(self, rounding=None, context=None): """Rounds to the nearest integer, without raising inexact, rounded.""" if context is None: context = getcontext() if rounding is None: rounding = context.rounding if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self) if self._exp >= 0: return Decimal(self) else: return self._rescale(0, rounding)
Rounds to the nearest integer, without raising inexact, rounded.
to_integral_value
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def sqrt(self, context=None): """Return the square root of self.""" if context is None: context = getcontext() if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() and self._sign == 0: return Decimal(self) if not self: # exponent = self._exp // 2. sqrt(-0) = -0 ans = _dec_from_triple(self._sign, '0', self._exp // 2) return ans._fix(context) if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') # At this point self represents a positive number. Let p be # the desired precision and express self in the form c*100**e # with c a positive real number and e an integer, c and e # being chosen so that 100**(p-1) <= c < 100**p. Then the # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) # <= sqrt(c) < 10**p, so the closest representable Decimal at # precision p is n*10**e where n = round_half_even(sqrt(c)), # the closest integer to sqrt(c) with the even integer chosen # in the case of a tie. # # To ensure correct rounding in all cases, we use the # following trick: we compute the square root to an extra # place (precision p+1 instead of precision p), rounding down. # Then, if the result is inexact and its last digit is 0 or 5, # we increase the last digit to 1 or 6 respectively; if it's # exact we leave the last digit alone. Now the final round to # p places (or fewer in the case of underflow) will round # correctly and raise the appropriate flags. # use an extra digit of precision prec = context.prec+1 # write argument in the form c*100**e where e = self._exp//2 # is the 'ideal' exponent, to be used if the square root is # exactly representable. l is the number of 'digits' of c in # base 100, so that 100**(l-1) <= c < 100**l. op = _WorkRep(self) e = op.exp >> 1 if op.exp & 1: c = op.int * 10 l = (len(self._int) >> 1) + 1 else: c = op.int l = len(self._int)+1 >> 1 # rescale so that c has exactly prec base 100 'digits' shift = prec-l if shift >= 0: c *= 100**shift exact = True else: c, remainder = divmod(c, 100**-shift) exact = not remainder e -= shift # find n = floor(sqrt(c)) using Newton's method n = 10**prec while True: q = c//n if n <= q: break else: n = n + q >> 1 exact = exact and n*n == c if exact: # result is exact; rescale to use ideal exponent e if shift >= 0: # assert n % 10**shift == 0 n //= 10**shift else: n *= 10**-shift e += shift else: # result is not exact; fix last digit as described above if n % 5 == 0: n += 1 ans = _dec_from_triple(0, str(n), e) # round, and fit to current context context = context._shallow_copy() rounding = context._set_rounding(ROUND_HALF_EVEN) ans = ans._fix(context) context.rounding = rounding return ans
Return the square root of self.
sqrt
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def max(self, other, context=None): """Returns the larger value. Like max(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ other = _convert_other(other, raiseit=True) if context is None: context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn == 0: return self._fix(context) if sn == 1 and on == 0: return other._fix(context) return self._check_nans(other, context) c = self._cmp(other) if c == 0: # If both operands are finite and equal in numerical value # then an ordering is applied: # # If the signs differ then max returns the operand with the # positive sign and min returns the operand with the negative sign # # If the signs are the same then the exponent is used to select # the result. This is exactly the ordering used in compare_total. c = self.compare_total(other) if c == -1: ans = other else: ans = self return ans._fix(context)
Returns the larger value. Like max(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds.
max
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def min(self, other, context=None): """Returns the smaller value. Like min(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ other = _convert_other(other, raiseit=True) if context is None: context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn == 0: return self._fix(context) if sn == 1 and on == 0: return other._fix(context) return self._check_nans(other, context) c = self._cmp(other) if c == 0: c = self.compare_total(other) if c == -1: ans = self else: ans = other return ans._fix(context)
Returns the smaller value. Like min(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds.
min
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _isinteger(self): """Returns whether self is an integer""" if self._is_special: return False if self._exp >= 0: return True rest = self._int[self._exp:] return rest == '0'*len(rest)
Returns whether self is an integer
_isinteger
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _iseven(self): """Returns True if self is even. Assumes self is an integer.""" if not self or self._exp > 0: return True return self._int[-1+self._exp] in '02468'
Returns True if self is even. Assumes self is an integer.
_iseven
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def adjusted(self): """Return the adjusted exponent of self""" try: return self._exp + len(self._int) - 1 # If NaN or Infinity, self._exp is string except TypeError: return 0
Return the adjusted exponent of self
adjusted
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def compare_signal(self, other, context=None): """Compares self to the other operand numerically. It's pretty much like compare(), but all NaNs signal, with signaling NaNs taking precedence over quiet NaNs. """ other = _convert_other(other, raiseit = True) ans = self._compare_check_nans(other, context) if ans: return ans return self.compare(other, context=context)
Compares self to the other operand numerically. It's pretty much like compare(), but all NaNs signal, with signaling NaNs taking precedence over quiet NaNs.
compare_signal
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def compare_total(self, other): """Compares self to other using the abstract representations. This is not like the standard compare, which use their numerical value. Note that a total ordering is defined for all possible abstract representations. """ other = _convert_other(other, raiseit=True) # if one is negative and the other is positive, it's easy if self._sign and not other._sign: return _NegativeOne if not self._sign and other._sign: return _One sign = self._sign # let's handle both NaN types self_nan = self._isnan() other_nan = other._isnan() if self_nan or other_nan: if self_nan == other_nan: # compare payloads as though they're integers self_key = len(self._int), self._int other_key = len(other._int), other._int if self_key < other_key: if sign: return _One else: return _NegativeOne if self_key > other_key: if sign: return _NegativeOne else: return _One return _Zero if sign: if self_nan == 1: return _NegativeOne if other_nan == 1: return _One if self_nan == 2: return _NegativeOne if other_nan == 2: return _One else: if self_nan == 1: return _One if other_nan == 1: return _NegativeOne if self_nan == 2: return _One if other_nan == 2: return _NegativeOne if self < other: return _NegativeOne if self > other: return _One if self._exp < other._exp: if sign: return _One else: return _NegativeOne if self._exp > other._exp: if sign: return _NegativeOne else: return _One return _Zero
Compares self to other using the abstract representations. This is not like the standard compare, which use their numerical value. Note that a total ordering is defined for all possible abstract representations.
compare_total
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def compare_total_mag(self, other): """Compares self to other using abstract repr., ignoring sign. Like compare_total, but with operand's sign ignored and assumed to be 0. """ other = _convert_other(other, raiseit=True) s = self.copy_abs() o = other.copy_abs() return s.compare_total(o)
Compares self to other using abstract repr., ignoring sign. Like compare_total, but with operand's sign ignored and assumed to be 0.
compare_total_mag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def copy_negate(self): """Returns a copy with the sign inverted.""" if self._sign: return _dec_from_triple(0, self._int, self._exp, self._is_special) else: return _dec_from_triple(1, self._int, self._exp, self._is_special)
Returns a copy with the sign inverted.
copy_negate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def copy_sign(self, other): """Returns self with the sign of other.""" other = _convert_other(other, raiseit=True) return _dec_from_triple(other._sign, self._int, self._exp, self._is_special)
Returns self with the sign of other.
copy_sign
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def is_normal(self, context=None): """Return True if self is a normal number; otherwise return False.""" if self._is_special or not self: return False if context is None: context = getcontext() return context.Emin <= self.adjusted()
Return True if self is a normal number; otherwise return False.
is_normal
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def is_subnormal(self, context=None): """Return True if self is subnormal; otherwise return False.""" if self._is_special or not self: return False if context is None: context = getcontext() return self.adjusted() < context.Emin
Return True if self is subnormal; otherwise return False.
is_subnormal
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _ln_exp_bound(self): """Compute a lower bound for the adjusted exponent of self.ln(). In other words, compute r such that self.ln() >= 10**r. Assumes that self is finite and positive and that self != 1. """ # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 adj = self._exp + len(self._int) - 1 if adj >= 1: # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) return len(str(adj*23//10)) - 1 if adj <= -2: # argument <= 0.1 return len(str((-1-adj)*23//10)) - 1 op = _WorkRep(self) c, e = op.int, op.exp if adj == 0: # 1 < self < 10 num = str(c-10**-e) den = str(c) return len(num) - len(den) - (num < den) # adj == -1, 0.1 <= self < 1 return e + len(str(10**-e - c)) - 1
Compute a lower bound for the adjusted exponent of self.ln(). In other words, compute r such that self.ln() >= 10**r. Assumes that self is finite and positive and that self != 1.
_ln_exp_bound
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def ln(self, context=None): """Returns the natural (base e) logarithm of self.""" if context is None: context = getcontext() # ln(NaN) = NaN ans = self._check_nans(context=context) if ans: return ans # ln(0.0) == -Infinity if not self: return _NegativeInfinity # ln(Infinity) = Infinity if self._isinfinity() == 1: return _Infinity # ln(1.0) == 0.0 if self == _One: return _Zero # ln(negative) raises InvalidOperation if self._sign == 1: return context._raise_error(InvalidOperation, 'ln of a negative value') # result is irrational, so necessarily inexact op = _WorkRep(self) c, e = op.int, op.exp p = context.prec # correctly rounded result: repeatedly increase precision by 3 # until we get an unambiguously roundable result places = p - self._ln_exp_bound() + 2 # at least p+3 places while True: coeff = _dlog(c, e, places) # assert len(str(abs(coeff)))-p >= 1 if coeff % (5*10**(len(str(abs(coeff)))-p-1)): break places += 3 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) context = context._shallow_copy() rounding = context._set_rounding(ROUND_HALF_EVEN) ans = ans._fix(context) context.rounding = rounding return ans
Returns the natural (base e) logarithm of self.
ln
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _log10_exp_bound(self): """Compute a lower bound for the adjusted exponent of self.log10(). In other words, find r such that self.log10() >= 10**r. Assumes that self is finite and positive and that self != 1. """ # For x >= 10 or x < 0.1 we only need a bound on the integer # part of log10(self), and this comes directly from the # exponent of x. For 0.1 <= x <= 10 we use the inequalities # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 adj = self._exp + len(self._int) - 1 if adj >= 1: # self >= 10 return len(str(adj))-1 if adj <= -2: # self < 0.1 return len(str(-1-adj))-1 op = _WorkRep(self) c, e = op.int, op.exp if adj == 0: # 1 < self < 10 num = str(c-10**-e) den = str(231*c) return len(num) - len(den) - (num < den) + 2 # adj == -1, 0.1 <= self < 1 num = str(10**-e-c) return len(num) + e - (num < "231") - 1
Compute a lower bound for the adjusted exponent of self.log10(). In other words, find r such that self.log10() >= 10**r. Assumes that self is finite and positive and that self != 1.
_log10_exp_bound
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def log10(self, context=None): """Returns the base 10 logarithm of self.""" if context is None: context = getcontext() # log10(NaN) = NaN ans = self._check_nans(context=context) if ans: return ans # log10(0.0) == -Infinity if not self: return _NegativeInfinity # log10(Infinity) = Infinity if self._isinfinity() == 1: return _Infinity # log10(negative or -Infinity) raises InvalidOperation if self._sign == 1: return context._raise_error(InvalidOperation, 'log10 of a negative value') # log10(10**n) = n if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): # answer may need rounding ans = Decimal(self._exp + len(self._int) - 1) else: # result is irrational, so necessarily inexact op = _WorkRep(self) c, e = op.int, op.exp p = context.prec # correctly rounded result: repeatedly increase precision # until result is unambiguously roundable places = p-self._log10_exp_bound()+2 while True: coeff = _dlog10(c, e, places) # assert len(str(abs(coeff)))-p >= 1 if coeff % (5*10**(len(str(abs(coeff)))-p-1)): break places += 3 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) context = context._shallow_copy() rounding = context._set_rounding(ROUND_HALF_EVEN) ans = ans._fix(context) context.rounding = rounding return ans
Returns the base 10 logarithm of self.
log10
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _islogical(self): """Return True if self is a logical operand. For being logical, it must be a finite number with a sign of 0, an exponent of 0, and a coefficient whose digits must all be either 0 or 1. """ if self._sign != 0 or self._exp != 0: return False for dig in self._int: if dig not in '01': return False return True
Return True if self is a logical operand. For being logical, it must be a finite number with a sign of 0, an exponent of 0, and a coefficient whose digits must all be either 0 or 1.
_islogical
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def logical_and(self, other, context=None): """Applies an 'and' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Applies an 'and' operation between self and other's digits.
logical_and
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def logical_or(self, other, context=None): """Applies an 'or' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Applies an 'or' operation between self and other's digits.
logical_or
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def logical_xor(self, other, context=None): """Applies an 'xor' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Applies an 'xor' operation between self and other's digits.
logical_xor
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def max_mag(self, other, context=None): """Compares the values numerically with their sign ignored.""" other = _convert_other(other, raiseit=True) if context is None: context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn == 0: return self._fix(context) if sn == 1 and on == 0: return other._fix(context) return self._check_nans(other, context) c = self.copy_abs()._cmp(other.copy_abs()) if c == 0: c = self.compare_total(other) if c == -1: ans = other else: ans = self return ans._fix(context)
Compares the values numerically with their sign ignored.
max_mag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def min_mag(self, other, context=None): """Compares the values numerically with their sign ignored.""" other = _convert_other(other, raiseit=True) if context is None: context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn == 0: return self._fix(context) if sn == 1 and on == 0: return other._fix(context) return self._check_nans(other, context) c = self.copy_abs()._cmp(other.copy_abs()) if c == 0: c = self.compare_total(other) if c == -1: ans = self else: ans = other return ans._fix(context)
Compares the values numerically with their sign ignored.
min_mag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def next_minus(self, context=None): """Returns the largest representable number smaller than itself.""" if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() == -1: return _NegativeInfinity if self._isinfinity() == 1: return _dec_from_triple(0, '9'*context.prec, context.Etop()) context = context.copy() context._set_rounding(ROUND_FLOOR) context._ignore_all_flags() new_self = self._fix(context) if new_self != self: return new_self return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), context)
Returns the largest representable number smaller than itself.
next_minus
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def next_plus(self, context=None): """Returns the smallest representable number larger than itself.""" if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() == 1: return _Infinity if self._isinfinity() == -1: return _dec_from_triple(1, '9'*context.prec, context.Etop()) context = context.copy() context._set_rounding(ROUND_CEILING) context._ignore_all_flags() new_self = self._fix(context) if new_self != self: return new_self return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), context)
Returns the smallest representable number larger than itself.
next_plus
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def next_toward(self, other, context=None): """Returns the number closest to self, in the direction towards other. The result is the closest representable number to self (excluding self) that is in the direction towards other, unless both have the same value. If the two operands are numerically equal, then the result is a copy of self with the sign set to be the same as the sign of other. """ other = _convert_other(other, raiseit=True) if context is None: context = getcontext() ans = self._check_nans(other, context) if ans: return ans comparison = self._cmp(other) if comparison == 0: return self.copy_sign(other) if comparison == -1: ans = self.next_plus(context) else: # comparison == 1 ans = self.next_minus(context) # decide which flags to raise using value of ans if ans._isinfinity(): context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign) context._raise_error(Inexact) context._raise_error(Rounded) elif ans.adjusted() < context.Emin: context._raise_error(Underflow) context._raise_error(Subnormal) context._raise_error(Inexact) context._raise_error(Rounded) # if precision == 1 then we don't raise Clamped for a # result 0E-Etiny. if not ans: context._raise_error(Clamped) return ans
Returns the number closest to self, in the direction towards other. The result is the closest representable number to self (excluding self) that is in the direction towards other, unless both have the same value. If the two operands are numerically equal, then the result is a copy of self with the sign set to be the same as the sign of other.
next_toward
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def number_class(self, context=None): """Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity """ if self.is_snan(): return "sNaN" if self.is_qnan(): return "NaN" inf = self._isinfinity() if inf == 1: return "+Infinity" if inf == -1: return "-Infinity" if self.is_zero(): if self._sign: return "-Zero" else: return "+Zero" if context is None: context = getcontext() if self.is_subnormal(context=context): if self._sign: return "-Subnormal" else: return "+Subnormal" # just a normal, regular, boring number, :) if self._sign: return "-Normal" else: return "+Normal"
Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity
number_class
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def rotate(self, other, context=None): """Returns a rotated copy of self, value-of-other times.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans if other._exp != 0: return context._raise_error(InvalidOperation) if not (-context.prec <= int(other) <= context.prec): return context._raise_error(InvalidOperation) if self._isinfinity(): return Decimal(self) # get values, pad if necessary torot = int(other) rotdig = self._int topad = context.prec - len(rotdig) if topad > 0: rotdig = '0'*topad + rotdig elif topad < 0: rotdig = rotdig[-topad:] # let's rotate! rotated = rotdig[torot:] + rotdig[:torot] return _dec_from_triple(self._sign, rotated.lstrip('0') or '0', self._exp)
Returns a rotated copy of self, value-of-other times.
rotate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def scaleb(self, other, context=None): """Returns self operand after adding the second value to its exp.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans if other._exp != 0: return context._raise_error(InvalidOperation) liminf = -2 * (context.Emax + context.prec) limsup = 2 * (context.Emax + context.prec) if not (liminf <= int(other) <= limsup): return context._raise_error(InvalidOperation) if self._isinfinity(): return Decimal(self) d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) d = d._fix(context) return d
Returns self operand after adding the second value to its exp.
scaleb
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def shift(self, other, context=None): """Returns a shifted copy of self, value-of-other times.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans if other._exp != 0: return context._raise_error(InvalidOperation) if not (-context.prec <= int(other) <= context.prec): return context._raise_error(InvalidOperation) if self._isinfinity(): return Decimal(self) # get values, pad if necessary torot = int(other) rotdig = self._int topad = context.prec - len(rotdig) if topad > 0: rotdig = '0'*topad + rotdig elif topad < 0: rotdig = rotdig[-topad:] # let's shift! if torot < 0: shifted = rotdig[:torot] else: shifted = rotdig + '0'*torot shifted = shifted[-context.prec:] return _dec_from_triple(self._sign, shifted.lstrip('0') or '0', self._exp)
Returns a shifted copy of self, value-of-other times.
shift
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _dec_from_triple(sign, coefficient, exponent, special=False): """Create a decimal instance directly, without any validation, normalization (e.g. removal of leading zeros) or argument conversion. This function is for *internal use only*. """ self = object.__new__(Decimal) self._sign = sign self._int = coefficient self._exp = exponent self._is_special = special return self
Create a decimal instance directly, without any validation, normalization (e.g. removal of leading zeros) or argument conversion. This function is for *internal use only*.
_dec_from_triple
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _raise_error(self, condition, explanation = None, *args): """Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) if error in self._ignored_flags: # Don't touch the flag return error().handle(self, *args) self.flags[error] = 1 if not self.traps[error]: # The errors define how to handle themselves. return condition().handle(self, *args) # Errors should only be risked on copies of the context # self._ignored_flags = [] raise error(explanation)
Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag.
_raise_error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _ignore_flags(self, *flags): """Ignore the flags, if they are raised""" # Do not mutate-- This way, copies of a context leave the original # alone. self._ignored_flags = (self._ignored_flags + list(flags)) return list(flags)
Ignore the flags, if they are raised
_ignore_flags
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _regard_flags(self, *flags): """Stop ignoring the flags, if they are raised""" if flags and isinstance(flags[0], (tuple,list)): flags = flags[0] for flag in flags: self._ignored_flags.remove(flag)
Stop ignoring the flags, if they are raised
_regard_flags
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def _set_rounding(self, type): """Sets the rounding type. Sets the rounding type, and returns the current (previous) rounding type. Often used like: context = context.copy() # so you don't change the calling context # if an error occurs in the middle. rounding = context._set_rounding(ROUND_UP) val = self.__sub__(other, context=context) context._set_rounding(rounding) This will make it round up for that operation. """ rounding = self.rounding self.rounding= type return rounding
Sets the rounding type. Sets the rounding type, and returns the current (previous) rounding type. Often used like: context = context.copy() # so you don't change the calling context # if an error occurs in the middle. rounding = context._set_rounding(ROUND_UP) val = self.__sub__(other, context=context) context._set_rounding(rounding) This will make it round up for that operation.
_set_rounding
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def create_decimal(self, num='0'): """Creates a new Decimal instance but using self as context. This method implements the to-number operation of the IBM Decimal specification.""" if isinstance(num, basestring) and num != num.strip(): return self._raise_error(ConversionSyntax, "no trailing or leading whitespace is " "permitted.") d = Decimal(num, context=self) if d._isnan() and len(d._int) > self.prec - self._clamp: return self._raise_error(ConversionSyntax, "diagnostic info too long in NaN") return d._fix(self)
Creates a new Decimal instance but using self as context. This method implements the to-number operation of the IBM Decimal specification.
create_decimal
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def create_decimal_from_float(self, f): """Creates a new Decimal instance from a float but rounding using self as the context. >>> context = Context(prec=5, rounding=ROUND_DOWN) >>> context.create_decimal_from_float(3.1415926535897932) Decimal('3.1415') >>> context = Context(prec=5, traps=[Inexact]) >>> context.create_decimal_from_float(3.1415926535897932) Traceback (most recent call last): ... Inexact: None """ d = Decimal.from_float(f) # An exact conversion return d._fix(self) # Apply the context rounding
Creates a new Decimal instance from a float but rounding using self as the context. >>> context = Context(prec=5, rounding=ROUND_DOWN) >>> context.create_decimal_from_float(3.1415926535897932) Decimal('3.1415') >>> context = Context(prec=5, traps=[Inexact]) >>> context.create_decimal_from_float(3.1415926535897932) Traceback (most recent call last): ... Inexact: None
create_decimal_from_float
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def add(self, a, b): """Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal('1.02E+4') >>> ExtendedContext.add(1, Decimal(2)) Decimal('3') >>> ExtendedContext.add(Decimal(8), 5) Decimal('13') >>> ExtendedContext.add(5, 5) Decimal('10') """ a = _convert_other(a, raiseit=True) r = a.__add__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal('1.02E+4') >>> ExtendedContext.add(1, Decimal(2)) Decimal('3') >>> ExtendedContext.add(Decimal(8), 5) Decimal('13') >>> ExtendedContext.add(5, 5) Decimal('10')
add
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def compare(self, a, b): """Compares values numerically. If the signs of the operands differ, a value representing each operand ('-1' if the operand is less than zero, '0' if the operand is zero or negative zero, or '1' if the operand is greater than zero) is used in place of that operand for the comparison instead of the actual operand. The comparison is then effected by subtracting the second operand from the first and then returning a value according to the result of the subtraction: '-1' if the result is less than zero, '0' if the result is zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) Decimal('-1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) Decimal('0') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) Decimal('0') >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) Decimal('1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) Decimal('1') >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) Decimal('-1') >>> ExtendedContext.compare(1, 2) Decimal('-1') >>> ExtendedContext.compare(Decimal(1), 2) Decimal('-1') >>> ExtendedContext.compare(1, Decimal(2)) Decimal('-1') """ a = _convert_other(a, raiseit=True) return a.compare(b, context=self)
Compares values numerically. If the signs of the operands differ, a value representing each operand ('-1' if the operand is less than zero, '0' if the operand is zero or negative zero, or '1' if the operand is greater than zero) is used in place of that operand for the comparison instead of the actual operand. The comparison is then effected by subtracting the second operand from the first and then returning a value according to the result of the subtraction: '-1' if the result is less than zero, '0' if the result is zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) Decimal('-1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) Decimal('0') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) Decimal('0') >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) Decimal('1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) Decimal('1') >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) Decimal('-1') >>> ExtendedContext.compare(1, 2) Decimal('-1') >>> ExtendedContext.compare(Decimal(1), 2) Decimal('-1') >>> ExtendedContext.compare(1, Decimal(2)) Decimal('-1')
compare
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def compare_signal(self, a, b): """Compares the values of the two operands numerically. It's pretty much like compare(), but all NaNs signal, with signaling NaNs taking precedence over quiet NaNs. >>> c = ExtendedContext >>> c.compare_signal(Decimal('2.1'), Decimal('3')) Decimal('-1') >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) Decimal('0') >>> c.flags[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) Decimal('NaN') >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) Decimal('NaN') >>> print c.flags[InvalidOperation] 1 >>> c.compare_signal(-1, 2) Decimal('-1') >>> c.compare_signal(Decimal(-1), 2) Decimal('-1') >>> c.compare_signal(-1, Decimal(2)) Decimal('-1') """ a = _convert_other(a, raiseit=True) return a.compare_signal(b, context=self)
Compares the values of the two operands numerically. It's pretty much like compare(), but all NaNs signal, with signaling NaNs taking precedence over quiet NaNs. >>> c = ExtendedContext >>> c.compare_signal(Decimal('2.1'), Decimal('3')) Decimal('-1') >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) Decimal('0') >>> c.flags[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) Decimal('NaN') >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) Decimal('NaN') >>> print c.flags[InvalidOperation] 1 >>> c.compare_signal(-1, 2) Decimal('-1') >>> c.compare_signal(Decimal(-1), 2) Decimal('-1') >>> c.compare_signal(-1, Decimal(2)) Decimal('-1')
compare_signal
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def divide(self, a, b): """Decimal division in a specified context. >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) Decimal('0.333333333') >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) Decimal('0.666666667') >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) Decimal('2.5') >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) Decimal('0.1') >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) Decimal('1') >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) Decimal('4.00') >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) Decimal('1.20') >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) Decimal('10') >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) Decimal('1000') >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) Decimal('1.20E+6') >>> ExtendedContext.divide(5, 5) Decimal('1') >>> ExtendedContext.divide(Decimal(5), 5) Decimal('1') >>> ExtendedContext.divide(5, Decimal(5)) Decimal('1') """ a = _convert_other(a, raiseit=True) r = a.__div__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
Decimal division in a specified context. >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) Decimal('0.333333333') >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) Decimal('0.666666667') >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) Decimal('2.5') >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) Decimal('0.1') >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) Decimal('1') >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) Decimal('4.00') >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) Decimal('1.20') >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) Decimal('10') >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) Decimal('1000') >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) Decimal('1.20E+6') >>> ExtendedContext.divide(5, 5) Decimal('1') >>> ExtendedContext.divide(Decimal(5), 5) Decimal('1') >>> ExtendedContext.divide(5, Decimal(5)) Decimal('1')
divide
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def divide_int(self, a, b): """Divides two numbers and returns the integer part of the result. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) Decimal('0') >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) Decimal('3') >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) Decimal('3') >>> ExtendedContext.divide_int(10, 3) Decimal('3') >>> ExtendedContext.divide_int(Decimal(10), 3) Decimal('3') >>> ExtendedContext.divide_int(10, Decimal(3)) Decimal('3') """ a = _convert_other(a, raiseit=True) r = a.__floordiv__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
Divides two numbers and returns the integer part of the result. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) Decimal('0') >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) Decimal('3') >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) Decimal('3') >>> ExtendedContext.divide_int(10, 3) Decimal('3') >>> ExtendedContext.divide_int(Decimal(10), 3) Decimal('3') >>> ExtendedContext.divide_int(10, Decimal(3)) Decimal('3')
divide_int
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def divmod(self, a, b): """Return (a // b, a % b). >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) (Decimal('2'), Decimal('2')) >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(Decimal(8), 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, Decimal(4)) (Decimal('2'), Decimal('0')) """ a = _convert_other(a, raiseit=True) r = a.__divmod__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
Return (a // b, a % b). >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) (Decimal('2'), Decimal('2')) >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(Decimal(8), 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, Decimal(4)) (Decimal('2'), Decimal('0'))
divmod
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def fma(self, a, b, c): """Returns a multiplied by b, plus c. The first two operands are multiplied together, using multiply, the third operand is then added to the result of that multiplication, using add, all with only one final rounding. >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) Decimal('22') >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) Decimal('-8') >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) Decimal('1.38435736E+12') >>> ExtendedContext.fma(1, 3, 4) Decimal('7') >>> ExtendedContext.fma(1, Decimal(3), 4) Decimal('7') >>> ExtendedContext.fma(1, 3, Decimal(4)) Decimal('7') """ a = _convert_other(a, raiseit=True) return a.fma(b, c, context=self)
Returns a multiplied by b, plus c. The first two operands are multiplied together, using multiply, the third operand is then added to the result of that multiplication, using add, all with only one final rounding. >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) Decimal('22') >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) Decimal('-8') >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) Decimal('1.38435736E+12') >>> ExtendedContext.fma(1, 3, 4) Decimal('7') >>> ExtendedContext.fma(1, Decimal(3), 4) Decimal('7') >>> ExtendedContext.fma(1, 3, Decimal(4)) Decimal('7')
fma
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def logical_and(self, a, b): """Applies the logical operation 'and' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) Decimal('1000') >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) Decimal('10') >>> ExtendedContext.logical_and(110, 1101) Decimal('100') >>> ExtendedContext.logical_and(Decimal(110), 1101) Decimal('100') >>> ExtendedContext.logical_and(110, Decimal(1101)) Decimal('100') """ a = _convert_other(a, raiseit=True) return a.logical_and(b, context=self)
Applies the logical operation 'and' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) Decimal('1000') >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) Decimal('10') >>> ExtendedContext.logical_and(110, 1101) Decimal('100') >>> ExtendedContext.logical_and(Decimal(110), 1101) Decimal('100') >>> ExtendedContext.logical_and(110, Decimal(1101)) Decimal('100')
logical_and
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def logical_or(self, a, b): """Applies the logical operation 'or' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) Decimal('1110') >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) Decimal('1110') >>> ExtendedContext.logical_or(110, 1101) Decimal('1111') >>> ExtendedContext.logical_or(Decimal(110), 1101) Decimal('1111') >>> ExtendedContext.logical_or(110, Decimal(1101)) Decimal('1111') """ a = _convert_other(a, raiseit=True) return a.logical_or(b, context=self)
Applies the logical operation 'or' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) Decimal('1110') >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) Decimal('1110') >>> ExtendedContext.logical_or(110, 1101) Decimal('1111') >>> ExtendedContext.logical_or(Decimal(110), 1101) Decimal('1111') >>> ExtendedContext.logical_or(110, Decimal(1101)) Decimal('1111')
logical_or
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def logical_xor(self, a, b): """Applies the logical operation 'xor' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) Decimal('1') >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) Decimal('0') >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) Decimal('110') >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) Decimal('1101') >>> ExtendedContext.logical_xor(110, 1101) Decimal('1011') >>> ExtendedContext.logical_xor(Decimal(110), 1101) Decimal('1011') >>> ExtendedContext.logical_xor(110, Decimal(1101)) Decimal('1011') """ a = _convert_other(a, raiseit=True) return a.logical_xor(b, context=self)
Applies the logical operation 'xor' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) Decimal('1') >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) Decimal('0') >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) Decimal('110') >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) Decimal('1101') >>> ExtendedContext.logical_xor(110, 1101) Decimal('1011') >>> ExtendedContext.logical_xor(Decimal(110), 1101) Decimal('1011') >>> ExtendedContext.logical_xor(110, Decimal(1101)) Decimal('1011')
logical_xor
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def max(self, a, b): """max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) Decimal('3') >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) Decimal('3') >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) Decimal('1') >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max(1, 2) Decimal('2') >>> ExtendedContext.max(Decimal(1), 2) Decimal('2') >>> ExtendedContext.max(1, Decimal(2)) Decimal('2') """ a = _convert_other(a, raiseit=True) return a.max(b, context=self)
max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) Decimal('3') >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) Decimal('3') >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) Decimal('1') >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max(1, 2) Decimal('2') >>> ExtendedContext.max(Decimal(1), 2) Decimal('2') >>> ExtendedContext.max(1, Decimal(2)) Decimal('2')
max
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def max_mag(self, a, b): """Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) Decimal('-10') >>> ExtendedContext.max_mag(1, -2) Decimal('-2') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal('-2') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal('-2') """ a = _convert_other(a, raiseit=True) return a.max_mag(b, context=self)
Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) Decimal('-10') >>> ExtendedContext.max_mag(1, -2) Decimal('-2') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal('-2') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal('-2')
max_mag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def min(self, a, b): """min compares two values numerically and returns the minimum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the minimum (closer to negative infinity) of the two operands is chosen as the result. >>> ExtendedContext.min(Decimal('3'), Decimal('2')) Decimal('2') >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) Decimal('-10') >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) Decimal('1.0') >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.min(1, 2) Decimal('1') >>> ExtendedContext.min(Decimal(1), 2) Decimal('1') >>> ExtendedContext.min(1, Decimal(29)) Decimal('1') """ a = _convert_other(a, raiseit=True) return a.min(b, context=self)
min compares two values numerically and returns the minimum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the minimum (closer to negative infinity) of the two operands is chosen as the result. >>> ExtendedContext.min(Decimal('3'), Decimal('2')) Decimal('2') >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) Decimal('-10') >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) Decimal('1.0') >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.min(1, 2) Decimal('1') >>> ExtendedContext.min(Decimal(1), 2) Decimal('1') >>> ExtendedContext.min(1, Decimal(29)) Decimal('1')
min
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def min_mag(self, a, b): """Compares the values numerically with their sign ignored. >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) Decimal('-2') >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) Decimal('-3') >>> ExtendedContext.min_mag(1, -2) Decimal('1') >>> ExtendedContext.min_mag(Decimal(1), -2) Decimal('1') >>> ExtendedContext.min_mag(1, Decimal(-2)) Decimal('1') """ a = _convert_other(a, raiseit=True) return a.min_mag(b, context=self)
Compares the values numerically with their sign ignored. >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) Decimal('-2') >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) Decimal('-3') >>> ExtendedContext.min_mag(1, -2) Decimal('1') >>> ExtendedContext.min_mag(Decimal(1), -2) Decimal('1') >>> ExtendedContext.min_mag(1, Decimal(-2)) Decimal('1')
min_mag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def multiply(self, a, b): """multiply multiplies two operands. If either operand is a special value then the general rules apply. Otherwise, the operands are multiplied together ('long multiplication'), resulting in a number which may be as long as the sum of the lengths of the two operands. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) Decimal('3.60') >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) Decimal('21') >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) Decimal('0.72') >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) Decimal('-0.0') >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) Decimal('4.28135971E+11') >>> ExtendedContext.multiply(7, 7) Decimal('49') >>> ExtendedContext.multiply(Decimal(7), 7) Decimal('49') >>> ExtendedContext.multiply(7, Decimal(7)) Decimal('49') """ a = _convert_other(a, raiseit=True) r = a.__mul__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
multiply multiplies two operands. If either operand is a special value then the general rules apply. Otherwise, the operands are multiplied together ('long multiplication'), resulting in a number which may be as long as the sum of the lengths of the two operands. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) Decimal('3.60') >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) Decimal('21') >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) Decimal('0.72') >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) Decimal('-0.0') >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) Decimal('4.28135971E+11') >>> ExtendedContext.multiply(7, 7) Decimal('49') >>> ExtendedContext.multiply(Decimal(7), 7) Decimal('49') >>> ExtendedContext.multiply(7, Decimal(7)) Decimal('49')
multiply
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def next_toward(self, a, b): """Returns the number closest to a, in direction towards b. The result is the closest representable number from the first operand (but not the first operand) that is in the direction towards the second operand, unless the operands have the same value. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.next_toward(Decimal('1'), Decimal('2')) Decimal('1.00000001') >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) Decimal('-0E-1007') >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) Decimal('-1.00000002') >>> c.next_toward(Decimal('1'), Decimal('0')) Decimal('0.999999999') >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) Decimal('0E-1007') >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) Decimal('-1.00000004') >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) Decimal('-0.00') >>> c.next_toward(0, 1) Decimal('1E-1007') >>> c.next_toward(Decimal(0), 1) Decimal('1E-1007') >>> c.next_toward(0, Decimal(1)) Decimal('1E-1007') """ a = _convert_other(a, raiseit=True) return a.next_toward(b, context=self)
Returns the number closest to a, in direction towards b. The result is the closest representable number from the first operand (but not the first operand) that is in the direction towards the second operand, unless the operands have the same value. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.next_toward(Decimal('1'), Decimal('2')) Decimal('1.00000001') >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) Decimal('-0E-1007') >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) Decimal('-1.00000002') >>> c.next_toward(Decimal('1'), Decimal('0')) Decimal('0.999999999') >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) Decimal('0E-1007') >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) Decimal('-1.00000004') >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) Decimal('-0.00') >>> c.next_toward(0, 1) Decimal('1E-1007') >>> c.next_toward(Decimal(0), 1) Decimal('1E-1007') >>> c.next_toward(0, Decimal(1)) Decimal('1E-1007')
next_toward
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT
def power(self, a, b, modulo=None): """Raises a to the power of b, to modulo if given. With two arguments, compute a**b. If a is negative then b must be integral. The result will be inexact unless b is integral and the result is finite and can be expressed exactly in 'precision' digits. With three arguments, compute (a**b) % modulo. For the three argument form, the following restrictions on the arguments hold: - all three arguments must be integral - b must be nonnegative - at least one of a or b must be nonzero - modulo must be nonzero and have at most 'precision' digits The result of pow(a, b, modulo) is identical to the result that would be obtained by computing (a**b) % modulo with unbounded precision, but is computed more efficiently. It is always exact. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.power(Decimal('2'), Decimal('3')) Decimal('8') >>> c.power(Decimal('-2'), Decimal('3')) Decimal('-8') >>> c.power(Decimal('2'), Decimal('-3')) Decimal('0.125') >>> c.power(Decimal('1.7'), Decimal('8')) Decimal('69.7575744') >>> c.power(Decimal('10'), Decimal('0.301029996')) Decimal('2.00000000') >>> c.power(Decimal('Infinity'), Decimal('-1')) Decimal('0') >>> c.power(Decimal('Infinity'), Decimal('0')) Decimal('1') >>> c.power(Decimal('Infinity'), Decimal('1')) Decimal('Infinity') >>> c.power(Decimal('-Infinity'), Decimal('-1')) Decimal('-0') >>> c.power(Decimal('-Infinity'), Decimal('0')) Decimal('1') >>> c.power(Decimal('-Infinity'), Decimal('1')) Decimal('-Infinity') >>> c.power(Decimal('-Infinity'), Decimal('2')) Decimal('Infinity') >>> c.power(Decimal('0'), Decimal('0')) Decimal('NaN') >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) Decimal('11') >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) Decimal('-11') >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) Decimal('1') >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) Decimal('11') >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) Decimal('11729830') >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) Decimal('-0') >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) Decimal('1') >>> ExtendedContext.power(7, 7) Decimal('823543') >>> ExtendedContext.power(Decimal(7), 7) Decimal('823543') >>> ExtendedContext.power(7, Decimal(7), 2) Decimal('1') """ a = _convert_other(a, raiseit=True) r = a.__pow__(b, modulo, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
Raises a to the power of b, to modulo if given. With two arguments, compute a**b. If a is negative then b must be integral. The result will be inexact unless b is integral and the result is finite and can be expressed exactly in 'precision' digits. With three arguments, compute (a**b) % modulo. For the three argument form, the following restrictions on the arguments hold: - all three arguments must be integral - b must be nonnegative - at least one of a or b must be nonzero - modulo must be nonzero and have at most 'precision' digits The result of pow(a, b, modulo) is identical to the result that would be obtained by computing (a**b) % modulo with unbounded precision, but is computed more efficiently. It is always exact. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.power(Decimal('2'), Decimal('3')) Decimal('8') >>> c.power(Decimal('-2'), Decimal('3')) Decimal('-8') >>> c.power(Decimal('2'), Decimal('-3')) Decimal('0.125') >>> c.power(Decimal('1.7'), Decimal('8')) Decimal('69.7575744') >>> c.power(Decimal('10'), Decimal('0.301029996')) Decimal('2.00000000') >>> c.power(Decimal('Infinity'), Decimal('-1')) Decimal('0') >>> c.power(Decimal('Infinity'), Decimal('0')) Decimal('1') >>> c.power(Decimal('Infinity'), Decimal('1')) Decimal('Infinity') >>> c.power(Decimal('-Infinity'), Decimal('-1')) Decimal('-0') >>> c.power(Decimal('-Infinity'), Decimal('0')) Decimal('1') >>> c.power(Decimal('-Infinity'), Decimal('1')) Decimal('-Infinity') >>> c.power(Decimal('-Infinity'), Decimal('2')) Decimal('Infinity') >>> c.power(Decimal('0'), Decimal('0')) Decimal('NaN') >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) Decimal('11') >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) Decimal('-11') >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) Decimal('1') >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) Decimal('11') >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) Decimal('11729830') >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) Decimal('-0') >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) Decimal('1') >>> ExtendedContext.power(7, 7) Decimal('823543') >>> ExtendedContext.power(Decimal(7), 7) Decimal('823543') >>> ExtendedContext.power(7, Decimal(7), 2) Decimal('1')
power
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/decimal.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/decimal.py
MIT